Reputation: 608
I'm working with the following function
MeanMatch <- function(df1, df2){
df2_means <- df2 %>% group_by(cyl) %>% summarise_all(mean,na.rm=TRUE)
TempJoined <- df1 %>% left_join(df2_means,by='cyl')
Now I have to specify the factor variable ('cyl' from mpg
dataset in library ggplot2). What I want to do is let the user supply the factor variable as a function argument, just once. Like:
MeanMatch <- function(df1, df2, FactorVar){
df2_means <- df2 %>% group_by(FactorVar) %>% summarise_all(mean,na.rm=TRUE)
TempJoined <- df1 %>% left_join(df2_means,by='FactorVar')
and if they want to use cyl from mpg then they can just write FactorVar=cyl
as argument. But of course the by='FactorVar'
part of the function doesn't work. How can I do this?
I don't mind solutions where I input it as MeanMatch(...,"cyl")
or MeanMatch(...,cyl)
.
Upvotes: 0
Views: 49
Reputation: 389235
Try using this function :
library(dplyr)
MeanMatch <- function(df1, df2, FactorVar){
df2_means <- df2 %>% group_by_at(FactorVar) %>% summarise_all(mean,na.rm=TRUE)
TempJoined <- df1 %>% left_join(df2_means,by=FactorVar)
}
and call it as :
MeanMatch(df1, df2,"cyl")
Upvotes: 1