![](/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.