将参数传递给 dplyr
Pass argument to dplyr
我想将参数传递给使用 dplyr
的函数。
想法是转换数据框的特定列(我的论点)的数据。
这是一个说明性的例子:
example = function(x){
df %>%
mutate( paste0(x, '_with_noise') = x + rnorm(n(), 0, 0.01))
}
问题是我收到此错误消息:
> Error: unexpected '=' in: " df %>%
> mutate( paste(x, '_with_noise', sep = '') ="
> > } Error: unexpected '}' in "}"
我也尝试使用这些,但我遇到了完全相同的错误。
mutate_
而不是 mutate
quote()
paste
命令在mutate
这里不起作用,所以最好将变量的名称分配给附加变量y
example = function(x){
y <- paste(x, '_with_noise', sep = '')
df %>%
mutate(y = x + rnorm(n(), 0, 0.01))
}
所以如果你的数据是
a <- c("A","B","C")
b <- c(2,3,4)
df <- data.frame(a,b)
> df
a b
1 A 2
2 B 3
3 C 4
打电话
> example(df$b)
导致结果
a b y
1 A 2 2.013845
2 B 3 2.998154
3 C 4 3.987750
要实现此技巧,您必须将整个命令放入 paste
函数中。
顺便说一句,最好使用 paste0
而不是 paste(..., sep = '')
这是一个工作示例。
example = function(x){
y <- as.character(substitute(x))
eval(parse(text = paste0(
"df %>% mutate(", y, "_with_noise =", y, " + rnorm(n(), 0, 0.01) )"
)))
}
set.seed(99)
df <- as.data.frame(matrix(sample(10, 25, T), ncol = 5,
dimnames = list(NULL, letters[1:5]) ))
example(b)
# a b c d e b_with_noise
# 1 6 10 6 7 3 9.996149
# 2 2 7 6 4 1 7.008946
# 3 7 3 2 2 9 2.991608
# 4 10 4 7 1 6 3.995421
# 5 6 2 7 2 8 2.001143
以下是您将如何使用 mutate_
。
example = function(x){
tx <- lazyeval::interp(~z+rnorm(n(), 0, 0.01), z=as.name(x))
tn <- paste0(x, '_with_noise')
df %>%
mutate_( .dots=setNames(list(tx), tn))
}
example("a")
example("b")
在 dplyr (vignette("nse","dplyr")
) 的 NSE 插图中有这方面的例子。此方法比粘贴任意字符串并评估结果更安全。
我想将参数传递给使用 dplyr
的函数。
想法是转换数据框的特定列(我的论点)的数据。
这是一个说明性的例子:
example = function(x){
df %>%
mutate( paste0(x, '_with_noise') = x + rnorm(n(), 0, 0.01))
}
问题是我收到此错误消息:
> Error: unexpected '=' in: " df %>%
> mutate( paste(x, '_with_noise', sep = '') ="
> > } Error: unexpected '}' in "}"
我也尝试使用这些,但我遇到了完全相同的错误。
mutate_
而不是mutate
quote()
paste
命令在mutate
这里不起作用,所以最好将变量的名称分配给附加变量y
example = function(x){
y <- paste(x, '_with_noise', sep = '')
df %>%
mutate(y = x + rnorm(n(), 0, 0.01))
}
所以如果你的数据是
a <- c("A","B","C")
b <- c(2,3,4)
df <- data.frame(a,b)
> df
a b
1 A 2
2 B 3
3 C 4
打电话
> example(df$b)
导致结果
a b y
1 A 2 2.013845
2 B 3 2.998154
3 C 4 3.987750
要实现此技巧,您必须将整个命令放入 paste
函数中。
顺便说一句,最好使用 paste0
而不是 paste(..., sep = '')
这是一个工作示例。
example = function(x){
y <- as.character(substitute(x))
eval(parse(text = paste0(
"df %>% mutate(", y, "_with_noise =", y, " + rnorm(n(), 0, 0.01) )"
)))
}
set.seed(99)
df <- as.data.frame(matrix(sample(10, 25, T), ncol = 5,
dimnames = list(NULL, letters[1:5]) ))
example(b)
# a b c d e b_with_noise
# 1 6 10 6 7 3 9.996149
# 2 2 7 6 4 1 7.008946
# 3 7 3 2 2 9 2.991608
# 4 10 4 7 1 6 3.995421
# 5 6 2 7 2 8 2.001143
以下是您将如何使用 mutate_
。
example = function(x){
tx <- lazyeval::interp(~z+rnorm(n(), 0, 0.01), z=as.name(x))
tn <- paste0(x, '_with_noise')
df %>%
mutate_( .dots=setNames(list(tx), tn))
}
example("a")
example("b")
在 dplyr (vignette("nse","dplyr")
) 的 NSE 插图中有这方面的例子。此方法比粘贴任意字符串并评估结果更安全。