12

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!

Tabasco
  • 131
  • 1
  • 1
  • 5
  • 2
    Don't use `assign()` to create many vars. Instead learn how to work with lists and functionals https://twitter.com/hadleywickham/status/535931179556691968 – Steven Beaupré Mar 06 '15 at 23:19
  • Whenever you have the urge to create sequentially named variables, you should be using a list instead: http://stackoverflow.com/a/24376207/903061 – Gregor Thomas Mar 06 '15 at 23:27
  • A fairly common question from new users is: How do I assign names to a group of similar objects?" Yes, you can do that, but you probably don't want to better is to: vectorize your thinking. Put all of the similar objects into one list. Subsequent analysis and manipulation is then going to be much smoother. [R Inferno](http://www.burns-stat.com/documents/books/the-r-inferno/) page 20. – Metrics Mar 07 '15 at 00:11
  • @Metrics Too bad that there is no example of such manipulation in the book – Julien Jul 05 '22 at 16:59

4 Answers4

11

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • 1
    Thanks a lot to you all for your helpful answers! The solution with call() works very well. I'll try the more R-ish strategies as soon as I understand what's really going on (I am spoiled by Stata and thinking in loops). – Tabasco Mar 07 '15 at 20:02
  • 1
    Ok, I upvoted your solution. I played with it...and now I want to upvote your solution for 1k times more. :) – Miha Trošt Aug 03 '18 at 14:10
1
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

Mahmut Ali ÖZKURAN
  • 1,120
  • 2
  • 23
  • 28
  • So If I've got this right, it assigns to variable name 1, the value of 4 (evalulating 2+2 without needing to be told to do so). – Mox Apr 05 '18 at 21:31
1

@MahmutAliÖZKURAN has answered your question about how to do this using a loop. A more "R-ish" way to accomplish this might be:

mapply(assign, <vector of variable names>, <vector of values>,
       MoreArgs = list(envir = .GlobalEnv))

Or, as in the case you specified above:

mapply(assign, paste0("varname", 1:2), <vector of values>,
       MoreArgs = list(envir = .GlobalEnv))
Richard Border
  • 3,209
  • 16
  • 30
0

I had the same issue and for some reason my apply's weren't working (lapply, assign directly, or my preferred goto, mclapply)

But this worked

vectorXTS <- mclapply(symbolstring,function(x)
    {
      df <- symbol_data_set[symbol_data_set$Symbol==x,]
      return(xts(as.data.frame(df[,-1:-2]),order.by=as.POSIXct(df$Date)))
    })

    names(symbolstring) <- symbolstring
    names(vectorXTS) <- symbolstring

    for(i in symbolstring) assign(symbolstring[i],vectorXTS[i])
thistleknot
  • 1,098
  • 16
  • 38