I am trying to write a function that will allow me to produce descriptive statistics by grouping across multiple factors in a data frame. I have spent way too many hours trying to get my function to recognize the by variables I am selecting.
Here is the fake data:
grouping1 <- c("red", "blue", "blue", "green", "red", "blue", "red", "green")
grouping2 <- c("high", "high", "low", "medium", "low", "high", "medium", "high")
value <- c(22,40,72,41,36,16,88,99)
fake_df <- data.frame(grouping1, grouping2, value)
Fake code example:
library(dplyr)
by_group_fun <- function(fun.data.in, fun.grouping.factor){
fake_df2 <- fun.data.in %>%
group_by(fun.grouping.factor) %>%
summarize(mean = mean(value), median = median(value))
fake_df2
}
by_group_fun(fake_df, grouping1)
by_group_fun(fake_df, grouping2)
This gives me:
Error in grouped_df_impl(data, unname(vars), drop) : Column `fun.grouping.factor` is unknown
Second try
I tried to assign the by variable selected in the function to a new variable and carry that forward.
Fake code example (second try):
by_group_fun2 <- function(fun.data.in, fun.grouping.factor){
fun.data.in$by_var <- fun.data.in$fun.grouping.factor
fake_df2 <- fun.data.in %>%
group_by(by_var) %>%
summarize(mean = mean(value), median = median(value))
fake_df2
}
by_group_fun2(fake_df, grouping1)
by_group_fun2(fake_df, grouping2)
This, the second try, gives me:
Error in grouped_df_impl(data, unname(vars), drop) : Column `by_var` is unknown
Use this example to guide you
Output