Question:
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 namedcar_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)) [/code]
Thevar
will change based on user input, so the resulting column will also changeHow do I do this in R?
Answer:
You could use:df[[calc_col]] <- abs(df[[var]] - lag(df[[var]], 12)) [/code]
If you have better answer, please add a comment about this, thank you!