magrittr中%&%;%和%,%之间有什么区别? [英] What is the difference between %>% and %,% in magrittr?

查看:200
本文介绍了magrittr中%&%;%和%,%之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

magrittr的Github开发版本包括一些很酷的管道新功能,但我没有完全了解%>%%,%之间的区别.这只是形式上带有%>%表示值,%,%表示函数,还是有些特殊之处?

Github developmental version of magrittr includes some cool new function for piping but I do not exactly catch de difference between %>% and %,%. Is this only formal with %>% for value and %,% for functions, or there is some specific peculiarity?

推荐答案

常规管道运算符为%>%.您可以使用%,%创建可重复使用的管道,即没有数据的管道.然后,您可以将同一管道与各种数据集一起使用.这是一个例子.

The normal piping operator is %>%. You can use %,% to create a reusable pipe, a pipe without data. Then later you can use the same pipe with various data sets. Here is an example.

library(magrittr)
library(dplyr)
library(Lahman)

假设您要根据总点击次数来计算排名前5位的棒球运动员.然后,您可以执行以下操作(取自magrittr自述文件):

Suppose you want to calculate the top 5 baseball players, according to total hits. Then you can do something like this (taken from the 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相同格式的多个数据集,因此可以再次使用同一管道. %,%帮助您创建,保存和重复使用管道:

So far so good. Now let's assume that you have several data sets in the same format as Batting, so you could just reuse the same pipe again. %,% helps you create, save and reuse the pipe:

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(...) ...)创建函数,但是%,%是更简洁的方法.

Of course you could also create a function the regular R way, i.e. top_total <- function(...) ..., but %,% is a more concise way.

这篇关于magrittr中%&%;%和%,%之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆