0

I have a DF with two columns and I would like to offset my second column with mutate. The problem is that column names are variable and I don't know how to use mutate in this case.

I tried to follow the example of this question, but I couldn't reach my goal.

Example:

df <- data.frame(x = 1:150, y = 1:150)

df %>%
    mutate(x = lag(x, 1))

My variable x changes its name with another DF's.

2 Answers2

1

Outside of a function, you might want to use the sym function with a bang-bang operator:

variable="Petal.Width"
df %>% mutate(x = lag(!!sym(variable), 1))

In a function, you can use the curly-curly ({{...}}) operator like this:

lag_df = function(df, variable){
  df %>% mutate(x = lag({{variable}}, 1))
}
iris %>% lag_df(Petal.Width) %>% select(x, Petal.Width)

{{variable}} is somehow similar to !!enquo(variable).

You can learn more about this in the "Programming with dplyr " vignette.

Dan Chaltiel
  • 5,597
  • 4
  • 36
  • 62
1

Another simple thing to do is to use .data to reference the data from the pipe. You can then select out the variable as usual with [[.

df <- data.frame(x = 1:150, y = 1:150)

variable <- "x"

df %>%
  mutate(x = lag(.data[[variable]], 1))
Adam
  • 4,810
  • 2
  • 8
  • 23