R: turning list items into objects
I hav开发者_如何学Ce a list of objects that I've created manually, like this:
rand1 <- rnorm(1e3)
rand2 <- rnorm(1e6)
myObjects <- NULL
myObjects[[1]] <-rand1
myObjects[[2]] <-rand2
names(myObjects) <- c("rand1","rand2")
I'm working on some code that bundles up objects and puts them up in S3. Then I have code in EC2 that I want to grab the myObjects list and 'unbundle' it automatically. In this example the list only has two objects and the names are known, but how do I code this to handle lists of any length and any names?
#pseudo code
for each thing in myObjects
thing <- myObjects[[thing]]
I can't quite figure out how to take names(myObjects)[1] and turn it into the name of an object for which I will assign the contents of myObjects[[1]]. I can handle the looping but creating each object kinda has me hung. I'm sure this is quite simple, but I can't quite grok it.
You can use assign
:
for(i in 1:length(myObjects)) assign(names(myObjects)[i], myObjects[[i]])
attach(myObjects)
To expand Shane's answer:
mapply(assign, names(myObjects), myObjects, MoreArgs=list(envir = globalenv())
(You may wish to change globalenv()
to another environment.)
精彩评论