String to variable name in R
r, string-concatenation
Solution
You can use `assign()`
var_name <- 'test'
assign(var_name,1:3)
test
Note: `assign` as such will create the variable in the environment it is called. So, if you were to call `assign` within a function like this:
myfun <- function(var) {
assign(eval(substitute(var)), 5)
print(get(var))
}
Calling the function assigns `my_var` a value of 5 within the function, whose environment is created only for the time the function is run and destroyed after.
> myfun("my_var")
# [1] 5
> my_var
# Error: object 'my_var' not found
So, if you want to retain the value after a function call, then, you'll have to specify an environment you'll have the variable thro' the time your task is run. For example, in the `global environment`:
myfun <- function(var, env = globalenv()) {
assign(eval(substitute(var)), 5, envir = env)
print(get(var))
}
> myfun("my_var")
# [1] 5
> my_var
# [1] 5
Problem
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!