%>% 在 R 中是什么意思 [英] What does %>% mean in R

查看:62
本文介绍了%>% 在 R 中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这个例子,server.R文件在这里.

我打算做一个类似的过滤器,但不知道 %>% 做了什么.

 # 应用过滤器m <- all_movies %>%筛选(评论 >= 评论,奥斯卡 >= 奥斯卡,年 >= 分钟,年 <= maxyear,票房 >= minboxoffice,票房 <= maxboxoffice)%>%安排(奥斯卡)

解决方案

中缀运算符 %>% 不是基础 R 的一部分,但实际上由包 magrittr 定义(CRAN)并且被<代码>dplyr(CRAN).>

它像烟斗一样工作,因此参考了马格利特的名画图像的背叛.

该函数的作用是将运算符的左侧传递给运算符右侧的第一个参数.在以下示例中,数据帧 iris 被传递给 head():

库(magrittr)虹膜%>%头部()萼片.长度 萼片.宽度 花瓣.长度 花瓣.宽度 种类1 5.1 3.5 1.4 0.2 山竹2 4.9 3.0 1.4 0.2 山竹3 4.7 3.2 1.3 0.2 刚毛4 4.6 3.1 1.5 0.2 山竹5 5.0 3.6 1.4 0.2 刚毛6 5.4 3.9 1.7 0.4 山竹

因此,iris %>% head() 等价于 head(iris).

通常,%>% 会被多次调用以将函数链接"在一起,从而实现与嵌套相同的结果.例如在下面的链中,iris 被传递给 head(),然后将结果传递给 summary().>

iris %>% head() %>% summary()

因此 iris %>% head() %>% summary() 等价于 summary(head(iris)).有些人更喜欢链接而不是嵌套,因为可以从左到右而不是从里到外读取应用的函数.

I am following this example, the server.R, file is here.

I plan to do a similar filter, but am lost as to what %>% does.

 # Apply filters
    m <- all_movies %>%
      filter(
        Reviews >= reviews,
        Oscars >= oscars,
        Year >= minyear,
        Year <= maxyear,
        BoxOffice >= minboxoffice,
        BoxOffice <= maxboxoffice
      ) %>%
      arrange(Oscars)

解决方案

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

这篇关于%>% 在 R 中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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