[英]errors when using R function using variables/column names as arguments to create a new variable using mutate and case_when
One area in R that I struggle with is specifying variable names in functions. R 中我遇到的一个问题是在函数中指定变量名。 I have seen examples and sometimes gotten them to work using {{argument}} or other approaches, but I don't really understand why some things work and others don't.我看过示例,有时使用 {{argument}} 或其他方法让它们工作,但我真的不明白为什么有些事情有效而其他事情却没有。 For example, I just tried to make a function that would use 2 variable values to generate a new variable.例如,我刚刚尝试制作一个 function,它将使用 2 个变量值来生成一个新变量。 Reproducible example below:下面的可重现示例:
look<-cars
twotoone<-function(v1,v2,nv){
look<-look %>% mutate(nv=case_when(
v1 > 4 & v2 > 4 ~ 1,
TRUE ~ 0
))
look<<-look
}
twotoone(speed,dist,allover4)
I get an error:我得到一个错误:
Error: Problem with
mutate()
columnnv
.错误:mutate()
列nv
有问题。 inv = case_when(v1 > 4 & v2 > 4 ~ 1, TRUE ~ 0)
. inv = case_when(v1 > 4 & v2 > 4 ~ 1, TRUE ~ 0)
。 x object 'speed' not found x object 未找到“速度”
If I put all arguments in quotes:如果我将所有 arguments 放在引号中:
twotoone('speed','dist','allover4')
there is no error, but the output data frame has the new variable nv instead of'allover4', and it's always =1 (no 0 assigned even when one of speed or distance are below 4).没有错误,但是 output 数据帧有新变量 nv 而不是 'allover4',它总是 =1(即使速度或距离之一低于 4 也不会分配 0)。 The same result happens if I just quote the first two arguments:如果我只引用前两个 arguments,也会出现同样的结果:
twotoone('speed','dist',allover4)
Any assistance to help me understand how I can expand the use of functions to help with recodes and composite variables, would be much appreciated.任何帮助我理解如何扩展函数的使用以帮助重新编码和复合变量的帮助,将不胜感激。 Thanks!!谢谢!!
We may use {{}}
- curly-curly operator which does the non-standard evaluation of passing unquoted arguments - previously it was done with enquo
+ !!
我们可以使用{{}}
- curly-curly 运算符,它对传递未引用的 arguments 进行非标准评估 - 以前它是用enquo
+ 完成的!!
. . Generally, the =
cannot do evaluation of expression on the lhs whereas the :=
operator in tidyverse can do it and that is the reason we use :=
通常, =
不能对 lhs 上的表达式求值,而 tidyverse 中的:=
运算符可以做到,这就是我们使用:=
的原因
twotoone<-function(dat, v1,v2,nv){
dat %>%
mutate({{nv}} := case_when(
{{v1}} > 4 & {{v2}} > 4 ~ 1,
TRUE ~ 0
))
}
-testing -测试
twotoone(cars, speed,dist,allover4)
speed dist allover4
1 4 2 0
2 4 10 0
3 7 4 0
4 7 22 1
5 8 16 1
6 9 10 1
...
Here is the version with ensym
and !!
这是带有ensym
和!!
的版本: :
twotoone<-function(df, v1,v2,nv){
v1 <- rlang::ensym(v1)
v2 <- rlang::ensym(v2)
nv <- rlang::ensym(nv)
df %>%
mutate(!!nv := case_when(
!!v1 > 4 & !!v2 > 4 ~ 1,
TRUE ~ 0
))
}
twotoone(cars, speed,dist,allover4)
speed dist allover4
<dbl> <dbl> <dbl>
1 4 2 0
2 4 10 0
3 7 4 0
4 7 22 1
5 8 16 1
6 9 10 1
7 10 18 1
8 10 26 1
9 10 34 1
10 11 17 1
# ... with 40 more rows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.