I have 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.
A list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);
The [[ operator can be used to extract single elements from a list. Here we extract the first element of the list. The [[ operator can also use named indices so that you don't have to remember the exact ordering of every element of the list. You can also use the $ operator to extract elements by name.
To convert a list to a vector in R use unlist() function. This function takes a list as one of the arguments and returns a Vector.
Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With