I need to use the function lag() to obtain a new column in a data frame, but within a loop. Therefore, the column names are given as a string. When I do it, I get only NAs. See below a very simplified and reproducible example. I removed the loop because it is not relevant.
df <-
data.frame(age = c(1, 2, 3),
value_2010 = c(10, 20, 30))
new_col_value <- "value_2010"
new_col_name <- "value_lag"
df_new_column <-
df%>%
mutate({{new_col_name}} := lag({{new_col_value}}))
This is what I want
And this is what I get
CodePudding user response:
You may use !!
instead of {{}}
df %>%
mutate(!!new_col_name := lag(!!as.symbol(new_col_value)))
age value_2010 value_lag
1 1 10 NA
2 2 20 10
3 3 30 20