Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: turning list items into objects

Tags:

list

r

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.

like image 977
JD Long Avatar asked Jun 22 '10 14:06

JD Long


People also ask

Can we convert list to object?

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);

How do I extract elements from a list in R?

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.

How do I turn a list into a vector in R?

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.

Can you have a vector of lists in R?

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.


3 Answers

You can use assign:

for(i in 1:length(myObjects)) assign(names(myObjects)[i], myObjects[[i]])
like image 82
Shane Avatar answered Sep 24 '22 12:09

Shane


attach(myObjects)

like image 24
hadley Avatar answered Sep 22 '22 12:09

hadley


To expand Shane's answer:

mapply(assign, names(myObjects), myObjects, MoreArgs=list(envir = globalenv())

(You may wish to change globalenv() to another environment.)

like image 44
Richie Cotton Avatar answered Sep 20 '22 12:09

Richie Cotton