library(tidyverse)
set.seed(041019)
我已经定义了一个简单的函数,它将 2 列加在一起,例如在这个例子中:
# data
dat <- data.frame("x" = sample(1:100, 10), "y" = sample(1:100, 10))
# define function
addXY <- function(dat) {
datOut <- dat %>%
mutate(z = x + y)
return(datOut)
}
addXY(dat)
x y z
1 80 30 110
2 28 16 44
3 11 61 72
4 37 24 61
5 29 44 73
6 62 33 95
7 94 50 144
8 59 59 118
9 88 39 127
10 65 78 143
假设我想向这个函数添加一个二进制参数,并使用它在 dplyr 链中进行有条件的过滤。我将如何正确地做到这一点。我试过这个但它不起作用:
addXY <- function(dat, aboveFifty = TRUE) {
datOut -> dat %>%
if (!aboveFifty) {filter(x < 50)} else {filter(x <= 100)} %>%
mutate(z = x + y)
return(datOut)
}
addXY(dat, aboveFifty = FALSE)
失败并显示错误消息:
Error in if (.) !aboveFifty else { :
argument is not interpretable as logical
In addition: Warning message:
In if (.) !aboveFifty else { :
the condition has length > 1 and only the first element will be used
看起来它正在尝试过滤参数而不是数据,这显然不是我想要的。