I have created a function in R that takes a fixed data-frame and uses dplyr to give me summary statistics (e.g., the mean of a particular variable) grouped by a chosen argument variable. Here is some code showing a toy data-frame and my function:
#Create data frame for analysis
DF <- data.frame(Type1 = c(0,0,1,1,0,1,1,0,1,0,1,1,1,0),
Type2 = c(1,1,1,1,1,1,2,2,2,2,3,3,3,3),
Output = c(4,2,7,5,1,1,7,8,3,2,5,4,3,6));
#Inspect the data-frame
DF;
Type1 Type2 Output
1 0 1 4
2 0 1 2
3 1 1 7
4 1 1 5
5 0 1 1
6 1 1 1
7 1 2 7
8 0 2 8
9 1 2 3
10 0 2 2
11 1 3 5
12 1 3 4
13 1 3 3
14 0 3 6
#Create a function that summarises the mean output grouped by input variable
MEAN_OUT <- function(VAR) { DF %>% group_by(!! sym(VAR)) %>%
summarise(Mean = mean(Output)) %>%
as.data.frame(); }
#Call the function grouping by variable 'Type1'
MEAN_OUT('Type1')
Type1 Mean
1 0 3.714286
2 1 4.444444
At the moment I can call MEAN_OUT('Type1') or MEAN_OUT('Type2') and these give me the correct summaries grouped by either of these argument variables. However, I would like to also be able to call MEAN_OUT(c('Type1','Type2')) to get a summary grouped over both variables. You can do this in the dplyr::group_by function, but I cannot figure out how to do it when this material is wrapped in my function. If I use my present function (shown above) to try to group by both variables I get the following error:
MEAN_OUT(c('Type1','Type2'))
Error: Only strings can be converted to symbols