Please let me know if this is a duplicate. I've looked over Stack and have found questions that are similar, but don't quite answer my question. I'm a beginner, so I appreciate anyone's help.
I am trying to add yearly summary variables to a data frame of monthly data (i.e, summing across rows). Here is an example data frame with limited monthly data.
df <- data.frame("Jan.2012" = c(1, 4, 5, 6), "Feb.2012" = c(3, 5, 7, 9),
"Jan.2013" = c(6, 8, 9, 10), "Feb.2013" = c(7, 5, 11, 13), "Jan.2014" = c(6, 8, 9, 11),
"Feb.2014" = c(7, 3, 5, 9))
The new variables would be named TotalYr2012, TotalYr2013, etc. For example, TotalYr2012 = c(4, 9, 12, 15), etc.
I am trying to iterate over a for loop (not best practice I know) to generate these variables. I know I am doing some things wrong with the assign statement as well as I get an error.
for (i in 2012:2014) {
varname <- paste("TotalYr", i, sep = "")
assign(df$varname, df %>% select(contains("i")) %>%
mutate(varname = sum()))
}
Thanks for your help!