I am trying to write a function that takes the name of a data frame and a column, which is summed with dplyr, and then returns a generic data frame. I tried a bunch of interp () permutations from the lazyeval package, but I spent too much time trying to get it to work. So, I wrote a βstaticβ version of the function that I want here:
summarize.df.static <- function(){
temp_df <- mtcars %>%
group_by(cyl) %>%
summarize(qsec = mean(qsec),
mpg=mean(mpg))
return(temp_df)
}
new_df <- summarize.df.static()
head(new_df)
Here is the beginning of the dynamic version I'm stuck on:
summarize.df.dynamic <- function(df_in,sum_metric_in){
temp_df <- df_in %>%
group_by(cyl) %>%
summarize_(qsec = mean(qsec),
sum_metric_in=mean(sum_metric_in))
return(temp_df)
}
new_df <- summarize.df.dynamic(mtcars,"mpg")
head(new_df)
Note that I want the column name in this example also come from the passed parameter (mpg in this case). Also note that the qsec column is static, that is, not passed.
The following is the correct answer sent by "docendo discimus":
summarize.df.dynamic<- function(df_in, sum_metric_in){
temp_df <- df_in %>%
group_by(cyl) %>%
summarize_(qsec = ~mean(qsec),
xyz = interp(~mean(var), var = as.name(sum_metric_in)))
names(temp_df)[names(temp_df) == "xyz"] <- sum_metric_in
return(temp_df)
}
new_df <- summarize.df.dynamic(mtcars,"mpg")
head(new_df)
new_df <- summarize.df.dynamic(mtcars,"disp")
head(new_df)