Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

r - dplyr without hard-coding the variable names

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The great Hadley Wickham himself (hallowed be his name!) suggested this on the mutatr Google Groups:

d <- expand.grid(1:3, 20:22)
my.variable <- 'Var1'
percent_rank <- function(x) rank(x)/max(rank(x))
call <- substitute(mutate(d, percent_rank(var)), 
                   list(var = as.name(my.variable)))
eval(call)
#   Var1 Var2 percent_rank(Var1)
# 1    1   20              0.250
# 2    2   20              0.625
# 3    3   20              1.000
# 4    1   21              0.250
# 5    2   21              0.625
# 6    3   21              1.000
# 7    1   22              0.250
# 8    2   22              0.625
# 9    3   22              1.000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...