I am cleaning a data set and I need to choose the variables depending on another variable. Let's say that if ID = 1, I need to introduce in the data frame the variable VAR01, if ID = 2, I need VAR02, and so on.
Thus, I'm doing a for loop where I paste the variable name 'VAR' with the ID number with the stringf function. The problem is that I need R to understand the string as a function name.
I've found in the forum this solution, which doesn't work for me:
> variable1 = c("monday", "tuesday", "wednesday")
> var_name = "variable1"
> eval(parse(text=var_name))
[1] "monday" "tuesday" "wednesday"
The problem is I cannot use it to refer to the variable:
> eval(parse(text=var_name)) = c(1,2,3)
Error in file(filename, "r") : cannot open the connection
In addition: Warning message:
In file(filename, "r") :
cannot open file 'variable1': No such file or directory
Has anyone got a solution?
Thanks!