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

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.

主站蜘蛛池模板: 阿城市| 深泽县| 鹿邑县| 钦州市| 手游| 四子王旗| 乳山市| 福州市| 临夏市| 金寨县| 时尚| 乌拉特后旗| 东台市| 东海县| 南京市| 林西县| 肇源县| 双流县| 辛集市| 平罗县| 墨玉县| 新巴尔虎左旗| 怀化市| 青岛市| 玉门市| 奉节县| 会理县| 广丰县| 浑源县| 通许县| 叶城县| 东兴市| 革吉县| 南乐县| 佛坪县| 青冈县| 洞头县| 淮南市| 马鞍山市| 息烽县| 治多县|