String to variable name in R

喜你入骨 提交于 2019-11-29 02:06:46
Rcoster

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

You can use get:

result = get(var_name)

Although heavy use of get and set suggests you might want to start using list's of variables instead:

l = list(variable1 = c(1,2,3))
l$variable1 = c(4,5,6) 

This is FAQ 7.21.

The most important part of that FAQ is the end where it tells you to use lists instead of doing this in the global environment. You mention that you want to do this in a data frame (which is already a list), so this becomes simpler. Try something like:

mydf <- data.frame( g=c('a','b','c') )
ID <- 1

mydf[[ sprintf("VAR%02d",ID) ]] <- 1:3
mydf

Using eval(parse(text=...)) in this case is like saying that you know how to get from New York City to Boston and therefore ask for directions from your origin to New York and directions from Boston to your destination. In some cases this might not be too bad, but it is a bit out of the way if you are trying to get from London to Paris (and your example has you going from New York to Boston via Mars). See fortune(106).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!