0

I want to store a column name in a variable and operate a dataframe based on that column name. For example if a I have two columns named car_sales and airplane_sales. I have a variable var that a user sets to say car_sales. i then calculate a new column like so:

calc_col <- paste0(var,"_delta")

df$calc_col <- abs(df$var - lag(df$var ,12))

The var will change based on user input, so the resulting column will also change

How do I do this in R?

thentangler
  • 1,048
  • 2
  • 12
  • 38

1 Answers1

1

You could use:

df[[calc_col]] <- abs(df[[var]] - lag(df[[var]], 12))
harre
  • 7,081
  • 2
  • 16
  • 28