I have a dataframe:
df <- data.frame(Category = c(rep("A", 3), rep("B", 3)), Value = rnorm(6))
df
Category Value
1 A -0.94968814
2 A 2.56687061
3 A -0.15665153
4 B -0.47647105
5 B 0.83015076
6 B -0.03744522
Now I want to add another column which is the mean per Category. This can be done with the dplyr package really easy:
df %>% group_by(Category) %>%
summarize(mean = mean(Value))
Now in piece of code my problem is: I can't use mean(Value)
, but I have a variable name that knows the column name: columnName = "Value"
But this unfortunately won't work:
columnName = "Value"
df %>% group_by(Category) %>%
summarize(mean = mean(columnName))
Warning messages: 1: In mean.default("Value") : argument is not numeric or logical: returning NA 2: In mean.default("Value") :
argument is not numeric or logical: returning NA
How can I pass the column name with the variable?