I wish to create a new column every time a grouped mean function is being called, for all the factor data types.
I am only able to replicate the decider result but only on a single factor variable A.
df <- data.frame(
target = c(1, 4, 8, 9, 2, 1, 3, 5, 7, 1),
A = c("A", "Z", "N", "A", "Z"),
B = c("B", "Q", "G", "B", "T"),
C = c("C", "Y", "C", "P", "Y")
)
grouped_mean <- function(data, summary_var, ...) {
summary_var <- enquo(summary_var)
data %>%
# Selects only factor data types and a target column
select(which(map_chr(., class) == "factor"), !!summary_var) %>%
group_by(...) %>%
# Over here I am not able to change column name, so that it yields Mean_A, Mean_B and Mean_C
mutate(mean = mean(!!summary_var)) %>%
ungroup()
}
grouped_mean(data = df,
group_var = A,
summary_var = target)
I tried looping it over:
map_df(df, grouped_mean(data = df, summary_var = target))
But I get this error:
Error: Can't convert a
tbl_df/tbl/data.frameobject to function
Questions and inputs:
- I am not sure how to make a function that dynamically changes name in a mutate function, from the name mean to mean_A, mean_B and mean_c
- I tried the map_df function to loop each element of the df, but unsuccessfully. The idea is to create new columns that are the means of the target feature.