是什么|>(管道大于)R 中的平均值? [英] What does |> (pipe greater than) mean in R?

查看:91
本文介绍了是什么|>(管道大于)R 中的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 R 中遇到了代码 |>.它是一个竖线字符(管道)后跟一个大于号.

I have recently come across the code |> in R. It is a vertical line character (pipe) followed by a greater than symbol.

这是一个例子:

mtcars |> head()

|> 代码在做什么?

推荐答案

|> 是基础 R 管道"操作员.它是4.1.0 版的新功能.

|> is the base R "pipe" operator. It was new in version 4.1.0.

简而言之,管道运算符提供运算符左侧 (LHS) 的结果作为右侧 (RHS) 的第一个参数.

In brief, the pipe operator provides the result of the left hand side (LHS) of the operator as the first argument of the right hand side (RHS).

考虑以下事项:

1:3 |> sum()
#[1] 6

这里,数字 1 到 3 的向量作为 sum 函数的第一个参数提供.

Here, the vector of numbers 1 through 3 is provided as the first argument of the sum function.

左侧的结果总是成为右侧调用的第一个参数.考虑:

The left hand side result always becomes the first argument of the right hand side call. Consider:

args(sum)
#function (..., na.rm = FALSE) 

c(1:3, NA_real_) |> sum(na.rm = TRUE)
#[1] 6

强调调用很重要,因为只要第一个参数命名,您就可以将LHS重定向到其他参数.考虑:

The emphasis on call is important because you can redirect the LHS to other arguments as long as the first argument is named. Consider:

args(rnorm)
#function (n, mean = 0, sd = 1) 
100 |> rnorm(n = 5)
#[1]  99.94718  99.93527  97.46838  97.38352 100.56502

args(sum)
#function (..., na.rm = FALSE) 
sum(na.rm = TRUE, ... = c(1:2,NA_real_))
#[1] 3
TRUE |> sum(... = c(1:2,NA_real_))
#[1] NA


使用 |> 运算符的一个好处是,与嵌套函数调用相比,它可以使代码在逻辑上更易于遵循:


One benefit of using the |> operator is that it can make code more easy to follow logically compared to nested function calls:

split(x = iris[-5], f = iris$Species) |>
  lapply(min) |>
  do.call(what = rbind) 
#           [,1]
#setosa      0.1
#versicolor  1.0
#virginica   1.4

#Compared to:
do.call(rbind,lapply(split(iris[-5],iris$Species),min))


此功能类似于 magrittr::%>% 运算符(也在 dplyr 中实现).

然而,与 %>% 不同的是,目前没有办法将 LHS 多次插入右侧或任意位置.Magrittr 使用 . 占位符作为 LHS 和 {} 来任意放置.

However, unlike %>%, there is no current way to pipe the LHS into the right hand side multiple times or into arbitrary positions. Magrittr uses the . placeholder for the LHS and {} to place it arbitrarily.

library(magrittr)
iris[iris$Sepal.Length > 7,] %>% subset(.$Species=="virginica")

TRUE %>% {sum(c(1:2,NA_real_),na.rm = .)}
[1] 3

此外,与基本的 R |> 不同,%>% 操作符可以在没有 () 的情况下通过管道进入函数调用:

Additionally, unlike the base R |>, the %>% operator can pipe into function calls without ():

1:3 |> sum
#Error: The pipe operator requires a function call as RHS

1:3 %>% sum
#[1] 6

这篇关于是什么|>(管道大于)R 中的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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