官术网_书友最值得收藏!

Ceci n'est pas une pipe

Now that we've covered tidy data, there is one more concept that is very common in the tidyverse that we should discuss. This is the pipe (%>%) from the magrittr package. This is similar to the Unix pipe, and it takes the left-hand side of the pipe and applies the right-hand side function to it. Take the following code:

mpg %>% summary()

The preceding code is equivalent to the following code:

summary(mpg)

As another example, look at the following code:

gapminder %>% filter(year > 1960)

The preceding code is equivalent to the following code:

filter(gapminder, year > 1960)

Piping greatly enhances the readability of code that requires several steps to execute. Take the following code:

x %>% f %>% g %>% h

The preceding code is equivalent to the following code:

h(g(f(x)))

To demonstrate with a real example, take the following code:

groupedData = gapminder %>%
filter(year > 1960) %>%
group_by(continent, year) %>%
summarise(meanLife = mean(lifeExp))

The preceding code is equivalent to the following code:

summarise(
group_by(
filter(gapminder, year > 1960),
continent, year),
meanLife = mean(lifeExp))

Hopefully, it should be obvious which is the easier to read of the two.

主站蜘蛛池模板: 砚山县| 隆子县| 周宁县| 济南市| 焉耆| 清徐县| 永昌县| 绩溪县| 安塞县| 丰台区| 延寿县| 麻江县| 富川| 辽阳市| 肥西县| 泸溪县| 晋州市| 罗源县| 遵化市| 曲周县| 孙吴县| 柳河县| 五台县| 鸡东县| 兴隆县| 香港| 博罗县| 湟中县| 马尔康县| 永胜县| 子洲县| 苍溪县| 安陆市| 太湖县| 曲靖市| 唐河县| 丹阳市| 嘉峪关市| 习水县| 五大连池市| 乌兰察布市|