lolibility
lolibility

Reputation: 2187

In R, how to use values as the variable names

I know the function get can help you transform values to variable names, like get(test[1]). But I find it is not compatible when the values is in a list format. Look at below example:

> A = c("obj1$length","obj1$width","obj1$height","obj1$weight")
> obj1 <- NULL
> obj1$length=c(1:4);obj1$width=c(5:8);obj1$height=c(9:12);obj1$weight=c(13:16)
> get(A[1])
Error in get(A[1]) : object 'obj1$length' not found

In this case, how can I retrieve the variable name?

Upvotes: 0

Views: 103

Answers (2)

Rufo
Rufo

Reputation: 534

I think that eval() function will do the trick, among other uses.

eval(A[1])

>[1] 1 2 3 4

You could also find useful this simple function I implemented (based in the commonly used combo eval, parse, paste):

evaluate<-function(..., envir=.GlobalEnv){ eval(parse(text=paste( ... ,sep="")), envir=envir) }

It concatenates and evaluates several character type objects. If you want it to be used inside another function, add at the begining of your function

envir <- environment()

and use it like this:

evaluate([some character objects], envir=envir)

Try, for example

myvariable1<-"aaa"; myvariable2<-"bbb"; aaa<-15; bbb<-3

evaluate(myvariable1," * ",myvariable2).

I find it very usefull when I have to evaluate similar sentences with several variables, or when I want to create variables with automatically generated names.

for(i in 1:100){evaluate("variable",i,"<-2*",i)}

Upvotes: 0

James
James

Reputation: 66834

get doesn't work like that you need to specify the variable and environment (the list is coerced to one) separately:

get("length",obj1)
[1] 1 2 3 4

Do do it with the data you have, you need to use eval and parse:

eval(parse(text=A[1]))
[1] 1 2 3 4

However, I suggest you rethink your approach to the problem as get, eval and parse are blunt tools that can bite you later.

Upvotes: 2

Related Questions