Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing string as column name in lag()

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And this is what I get

enter image description here

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading