0

I have some code and I want to make it easier to update which column in my data it acts on. At the moment it basically does something with one column and I want to make it super easy to change which column that is.

I was hoping to be able to have a little inputs section at the start of the code where I defined the column name as something and then reference that throughout the code instead of having the column name hardcoded throughout the code.

For example, if the column I want to work with is currently in my dataframe and called "Have", I want this line at the start:

Have_column <- "Have"

Then when I want to do something to this column I want to be referring to the Have_column value, such that when I want to change which column the code acts on all I have to do is change the "Have" to a different column name at the start of my code.

But I'm struggling to figure out how to refer to this where I have code like:

df$Have <- as.numeric(as.character(df$Have))

I figure I could do it all this way:

Have_column <- "Have"

df <- df %>% rename(Use  := all_of(Have_column))
df$Use <- as.numeric(as.character(df$Use))

But is there a way of referring to the column heading using the Have_column value?

Something like this gets me halfway:

Have_column <- "Have"
df$Use <- as.numeric(as.character(paste0("df$",all_of(Have_column))))

But trying to go the full way with this idea isn't working:

Have_column <- "Have"
paste0("df$",all_of(Have_column)) <- as.numeric(as.character(paste0("df$",all_of(Have_column))))

Any ideas welcome!

uwd
  • 45
  • 6

0 Answers0