Is it possible to use dplyr's mutate function without hard-coding the variable names? For example, the following code works, because I hard-code the name Var1:
> d=expand.grid(1:3, 20:22)
> d
Var1 Var2
1 1 20
2 2 20
3 3 20
4 1 21
5 2 21
6 3 21
7 1 22
8 2 22
9 3 22
> d=mutate(d, x=percent_rank(Var1))
> d
Var1 Var2 x
1 1 20 0.000
2 2 20 0.375
3 3 20 0.750
4 1 21 0.000
5 2 21 0.375
6 3 21 0.750
7 1 22 0.000
8 2 22 0.375
9 3 22 0.750
However, when I make the variable's name a variable, it no longer works:
> my.variable='Var1'
> d=mutate(d, x=percent_rank(my.variable))
> d
Var1 Var2 x
1 1 20 NaN
2 2 20 NaN
3 3 20 NaN
4 1 21 NaN
5 2 21 NaN
6 3 21 NaN
7 1 22 NaN
8 2 22 NaN
9 3 22 NaN
The eval() and as.symbol() functions don't seem to help, either.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…