Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - using variable column names in dplyr summarise

I found this question already asked but without proper answer. R using variable column names in summarise function in dplyr

I want to calculate the difference between two column means, but the column name should be provided by variables... So far I found only the function as.name to provide column names as text, but this somehow doesn't work here...

With fix column names it works.

x <- c('a','b')
df <- group_by(data.frame(a=c(1,2,3,4), b=c(2,3,4,5), c=c(1,1,2,2)), c)
df %>% summarise(mean(a) - mean(b))

With variable columns, it doesn't work

df %>% summarise(mean(x[1]) - mean(x[2]))
df %>% summarise(mean(as.name(x[1])) - mean(as.name(x[2])))

Since this was asked already 3 years ago and dplyr is under good development, I am wondering if there is an answer to this now.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use base::get:

df %>% summarise(mean(get(x[1])) - mean(get(x[2])))

# # A tibble: 2 x 2
#        c `mean(a) - mean(b)`
#    <dbl>               <dbl>
# 1     1                  -1
# 2     2                  -1

get will search in current environment by default.

As the error message says, mean expects a logical or numeric object, as.name returns a name:

class(as.name("a")) # [1] "name"

You could evaluate your name, that would work as well :

df %>% summarise(mean(eval(as.name(x[1]))) - mean(eval(as.name(x[2]))))
# # A tibble: 2 x 2
#       c `mean(eval(as.name(x[1]))) - mean(eval(as.name(x[2])))`
#   <dbl>                                                   <dbl>
# 1     1                                                      -1
# 2     2                                                      -1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...