Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

treat string as object name in a loop in R

I want to create a string in a loop and use this string as object in this loop. Here is a simplified example:

for (i in 1:2) {
  x <- paste("varname",i, sep="")
  x <- value
}

the loop should create varname1, varname2. Then I want to use varname1, varname2 as objects to assign values. I tried paste(), print() etc. Thanks for help!

like image 796
Tabasco Avatar asked Mar 06 '15 23:03

Tabasco


2 Answers

You could create the call() to <- and then evaluate it. Here's an example,

value <- 1:5

for (i in 1:2) {
    x <- paste("varname",i, sep="")
    eval(call("<-", as.name(x), value))
}

which creates the two objects varname1 and varname2

varname1
# [1] 1 2 3 4 5
varname2
# [1] 1 2 3 4 5

But you should really try to avoid assigning to the global environment from with in a method/function. We could use a list along with substitute() and then we have the new variables together in the same place.

f <- function(aa, bb) {
    eval(substitute(a <- b, list(a = as.name(aa), b = bb)))
}

Map(f, paste0("varname", 1:2), list(1:3, 3:6))
# $varname1
# [1] 1 2 3
#
# $varname2
# [1] 3 4 5 6
like image 84
Rich Scriven Avatar answered Sep 28 '22 04:09

Rich Scriven


assign("variableName", 5)

would do that.

For example if you have variable names in array of strings you can set them in loop as:

assign(varname[1], 2 + 2)

More and more information

https://stat.ethz.ch/R-manual/R-patched/library/base/html/assign.html

like image 34
Mahmut Ali ÖZKURAN Avatar answered Sep 28 '22 04:09

Mahmut Ali ÖZKURAN