![](/img/trans.png)
[英]What is the difference between the “+” operator in ggplot2 and the “%>%” operator in magrittr?
[英]What is the difference between %>% and %,% in magrittr?
github magrittr的开发版本包含一些很酷的管道新功能,但我并没有完全理解%>%
和%,%
之间的区别。 这只是正式的, %>%
的值和%,%
的函数,还是有一些特殊的特性?
正常的管道运营商是%>%
。 您可以使用%,%
来创建可重用的管道,没有数据的管道。 然后,您可以使用与各种数据集相同的管道。 这是一个例子。
library(magrittr)
library(dplyr)
library(Lahman)
假设您想根据总命中数计算前5名棒球运动员。 然后你可以做这样的事情(取自magrittr README):
Batting %>%
group_by(playerID) %>%
summarise(total = sum(G)) %>%
arrange(desc(total)) %>%
head(5)
# Source: local data frame [5 x 2]
#
# playerID total
# 1 rosepe01 3562
# 2 yastrca01 3308
# 3 aaronha01 3298
# 4 henderi01 3081
# 5 cobbty01 3035
到现在为止还挺好。 现在让我们假设您有几个与Batting
相同格式的数据集,因此您可以再次重用相同的管道。 %,%
可以帮助您创建,保存和重用管道:
top_total <- group_by(playerID) %,%
summarise(total = sum(G)) %,%
arrange(desc(total)) %,%
head(5)
top_total(Batting)
# Source: local data frame [5 x 2]
#
# playerID total
# 1 rosepe01 3562
# 2 yastrca01 3308
# 3 aaronha01 3298
# 4 henderi01 3081
# 5 cobbty01 3035
当然你也可以创建常规R方式的函数,即top_total <- function(...) ...
,但%,%
是一种更简洁的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.