没有参数的用户定义函数,在 R 中,在管道中

User-defined function with no arguments, in R, in pipe

我想写一个没有参数的函数,并且可以在管道中引用(%>%),这样我就不用重复几行代码了。但是,经过多次尝试后我没有得到它。我也希望能帮助您编写管道中引用的带有参数的函数。非常感谢您的帮助!简化示例如下:

library(tidyverse)
a <- c(1:10)
b <- c(11:20)
c <- data.frame(a, b)
c
#>     a  b
#> 1   1 11
#> 2   2 12
#> 3   3 13
#> 4   4 14
#> 5   5 15
#> 6   6 16
#> 7   7 17
#> 8   8 18
#> 9   9 19
#> 10 10 20
y <- function() {
  filter(d<5)
}

c %>% mutate(d = a*b) %>% y()
#> Error in y(.): unused argument (.)

reprex package (v0.3.0)

于 2020-08-16 创建

pipe 认为函数的第一个参数是数据,例如 mutate 或 filter 的第一个参数都是数据。所以当你做 mtcars %>% mutate(a = 5) 你实际上是在做 mutate(mtcars, a = 5).

因此您必须将其修改为:

y <- function(data) {
  filter(data, d < 80)
}

c %>% mutate(d = a*b) %>% y()

  a  b  d
1 1 11 11
2 2 12 24
3 3 13 39
4 4 14 56
5 5 15 75