0

In a loop, I would like to load data which has names g406, g407, g408... but I would like to write these directly into objects named 406, 407, 408.

 406 <- load("\g406.RData")

saves a string "\g406.RData" in the object 406. How can I save the g406.RData in the object 406 without any further lines of code to use it in a loop with indexes 406, 407, 408,.... Or alternatively, how can I save an R object named with a number is this possible?

S Front
  • 333
  • 1
  • 8
  • 1
    `load` doesn't really allow this because you can have many objects stored in an Rdata file. rds files a better if you have just one object. Are you absolutely sure there is only one object per Rdata file in your case? Also variable name in R cannot be purely numeric. You'd be better off storing items in a named list of some sort. – MrFlick Apr 16 '19 at 16:31

2 Answers2

1

You can use the assign() function

rdata <- load("\g406.RData")
assign("406", get(rdata))
cropgen
  • 1,920
  • 15
  • 24
  • Well, `load()` doesn't actually return the object it loads. It return the name of the object it loaded. But even then, you'd have to always escape this non standard name when using it like `\`400\`` which would be unpleasant to work with. – MrFlick Apr 16 '19 at 16:33
  • Fixed using `get()`. Thanks for pointing it out. – cropgen Apr 16 '19 at 16:39
0

I just found out after a long search that newname <- get(load('saved.file.rda')) also lets one save it as a different object.

S Front
  • 333
  • 1
  • 8
  • Well, it copies it to a new object. The original value, whatever it was called in the rdata file, will still be in your global environment. – MrFlick Apr 16 '19 at 16:34