1

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

And this is what I get

enter image description here

ungatoverde
  • 161
  • 12

1 Answers1

1

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
Park
  • 14,771
  • 6
  • 10
  • 29
  • I thought that dplyr v.1.0 supports the use of {{}}. See https://stackoverflow.com/questions/26003574/use-dynamic-variable-names-in-dplyr – ungatoverde Dec 15 '21 at 06:13
  • @ungatoverde I thought I should use `{{}}`, but this time, version 1.0.7, `!!` works for me. – Park Dec 15 '21 at 06:18
  • Ok. Thanks. It is interesting, because actually `{{new_col_name}}:=` works fine. But for some reason {{}} does not work within lag. Maybe an update in lag is missing. – ungatoverde Dec 15 '21 at 06:32
  • @ungatoverde Yes for `new_col_name` works fine but as you said, there might be problem with `lag` function, it works with `mean` in your link. – Park Dec 15 '21 at 06:34
  • @ungatoverde `{{` works if you wrap it in a function. `f = \(df, col) df %>% mutate("{{col}}_lag" := lag({{ col }}))` , then `f(df, value_2010)`. `{{` is shorthand for `enquo(x) !!x` ` – Donald Seinen Dec 15 '21 at 06:37