I try to create a variable with paste() in a mutate_() function (dplyr).
I try to adapt code with this answer (dplyr - mutate: use dynamic variable names) but it doesn't work ...
NB: nameVarPeriod1 is a param of a function.
nameVarPeriod1=A2
df <- df %>%
group_by(segment) %>%
mutate_((.dots=setNames(mean(paste0("Sum",nameVarPeriod1)), paste0("MeanSum",nameVarPeriod1))))
This returns a warning :
Warning message:
In mean.default(paste0("Sum", nameVarPeriod1)) :
argument is not numeric or logical: returning NA
How to evaluate the string in paste0 as variable name ?
When I replace the paste0 by this it works fine :
df <- df %>%
group_by(segment) %>%
mutate(mean=mean(SumA2))
DATA :
structure(list(segment = structure(c(5L, 1L, 4L, 2L, 2L, 14L,
11L, 6L, 14L, 1L), .Label = c("Seg1", "Seg2", "Seg3", "Seg4",
"Seg5", "Seg6", "Seg7", "Seg8", "Seg9", "Seg10", "Seg11", "Seg12",
"Seg13", "Seg14"), class = "factor"), SumA2 = c(107584.9, 127343.87,
205809.54, 138453.4, 24603.46, 44444.39, 103672, 88695.8, 64400,
36815.82)), .Names = c("segment", "SumA2"), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
df
– Chrisdf <- df %>% group_by(segment) %>% mutate(mean=mean(SumA2))
A new column "MeanSumA2" which is the mean of segment – Cox Tox