简体   繁体   中英

using value of a variable rather than the variable name to assign to in R in a loop

After hours of googling and trying, I'm still stuck... so hopefully someone can help out. I'm still beginner at R, and pretty sure there is a simple answer to this. I have the following code:

gamenumber <- 0
for(i in 1:9) {
  gamenumber <- paste("game201702000", toString(i), sep = "")
  gamelinknumber <- paste("201702000", toString(i), sep = "")
  gamelink <- paste("http://statsapi.web.nhl.com/api/v1/game/",gamelinknumber,"/feed/live", sep="")

  gamenumber <- fromJSON(gamelink)
}

My intent is that I go through the loop, creating a new gamenumber and gamelink every time, and write the content of the link page to the gamenumber. However, R writes to content from the gamelink to "gamenumber", rather than the value gamenumber is representing.

I want to end up with: VALUES panel in Rstudio

  • game2017020001 Large list (6 elements, 1.1 Mb)
  • game2017020002 Large list (6 elements, 1.1 Mb)
  • game2017020003 Large list (6 elements, 1.1 Mb)
  • ...
  • game2017020009 Large list (6 elements, 1.1 Mb)

but I end up with:

  • gamenumber Large list (6 elements, 1.1 Mb)

I have tried get, paste, and other things I found and thought were the solution.

Can anyone help?

I believe you want to use assign()

for(i in 1:9) {
  gamenumber <- paste("game201702000", toString(i), sep = "")
  gamelinknumber <- paste("201702000", toString(i), sep = "")
  gamelink <- paste("http://statsapi.web.nhl.com/api/v1/game/", gamelinknumber, "/feed/live", sep="")

  assign(gamenumber, fromJSON(gamelink))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM