使用 R |> 管道链接算术运算符

Tri*_*tio 4 r arithmetic-expressions pipe

这基本上与dplyr with %>% pipeline 中的链算术运算符相同的问题,但针对新的(如 R 4.1)管道运算符进行了更新|>

如何将算术运算符与 R 本机管道链接起来|>使用 dplyr/magrittr,您可以对算术运算符使用反引号,但这不适用于内置的 R 管道运算符。这是一个简单的例子:

R.version$version.string
# [1] "R version 4.2.2 (2022-10-31 ucrt)"

x <- 2
# With dplyr/magrittr, you can use backticks for arithmetic operators
x %>% `+`(2)
# [1] 4

# But that doesn't work with the inbuilt R pipe operator
x |> `+`(2)
#  Error: function '+' not supported in RHS call of a pipe
Run Code Online (Sandbox Code Playgroud)

希望答案足够通用,适用于通常不能与本机 R 管道很好地配合的任何运算符或内置函数(我的版本是 R 4.2.2)。

答案/sf/answers/5046054471/有很多关于%>%和之间的差异的有用信息|>,但没有一个能完全回答我的问题。

jay*_*.sf 6

我们可以使用命名空间前缀。

2 |> base::`+`(2)
# 4
Run Code Online (Sandbox Code Playgroud)