I'm trying to write a function that creates a new count variable within a certain year range. The input in the function would specify what years to count. I've got a dataframe with events, and count the events that happen up to age 12, age 13, age 14, etc. Here's what the basic setup looks like.
year.count <- function(age) {
var.name <- paste0("total_", as.character(age))
counts <- event_df %>%
filter(year <= (yob + age)) %>%
group_by(id) %>%
count() %>%
rename(eval(parse(text = var.name)) = n)
indiv_df <- indiv_df %>%
left_join(counts, by = "id")
return(indiv_df)
}
What I'm stuck on is the rename() part of the function. I cannot get any type of string to pass through as a variable name. Ideally, if age = 12 then the new variable name should be total_12. I've tried every option on this page: Pass a string as variable name in dplyr::filter. But I keep getting the same error:
Error: unexpected '=' in:
" count() %>%
mutate(eval(parse(text='scream')) ="
The text = scream is just a reflection of my current frustration, but I keep getting this unexpected '=' error with every variation of eval/pars/as.symbol/etc. Help!