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 write a function with column names as inputs

I'm writing a function that I'm going to use on multiple columns in dplyr, but I'm having trouble passing column names as inputs to functions for dplyr.

Here's an example of what I want to do:

df<-tbl_df(data.frame(group=rep(c("A", "B"), each=3), var1=sample(1:100, 6), var2=sample(1:100, 6)))


example<-function(colname){
  df %>%
    group_by(group)%>%
    summarize(output=mean(sqrt(colname)))%>%
    select(output)
}
example("var1")

Output should look like

df %>%
  group_by(group)%>%
  summarize(output=mean(sqrt(var1)))%>%
  select(output)

I've found a few similar questions, but nothing that I could directly apply to my problem, so any help is appreciated. I've tried some solutions involving eval, but I honestly don't know what exactly I'm supposed to be passing to eval.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Is this what you expected?

df<-tbl_df(data.frame(group=rep(c("A", "B"), each=3), var1=sample(1:100, 6), var2=sample(1:100, 6)))

example<-function(colname){
  df %>%
    group_by(group)%>%
    summarize(output=mean(sqrt(colname)))%>%
    select(output)
}
example( quote(var1) )
#-----
Source: local data frame [2 x 1]

    output
1 7.185935
2 8.090866

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

...