[Q.] How to create an array of lists, or structures the most elegant way? There have been questions in the past but none too recently...I want to know if the following looks OK to you guys or if there is a better way to create an array of lists: # PREAMBLE ... JUST TO GET THINGS GOING makeList<- function(data, anythingElse) { rval <- list( data = data, anythingElse = anythingElse ) class(rval) <- "myListOfArbitraryThings" return(rval) } # make up some arbitrary data payload<- list( as.matrix(cbind(1,1:3)), 10:15, data.frame(cbind(x=1, y=1:10), fac=sample(LETTERS[1:3], 10, repl=TRUE)) ) # HERE'S THE ARRAY-CONSTRUCTION PART THAT I WANT CRITIQUED: n<- 3 # number of lists in the array of lists v<- vector("list", n) # <--- IS THIS THE BEST WAY TO CREATE AN ARRAY OF LISTS? # fill the array with essentially arbitrary stuff: for (i in 1:n) v[[i]]<- makeList(payload[[i]], i) Thanks, Jack. --------------------------------- [[alternative HTML version deleted]]
Gabor Grothendieck
2005-Dec-06 14:05 UTC
[R] array of lists? is this the best way to do it?
On 12/6/05, John McHenry <john_d_mchenry at yahoo.com> wrote:> [Q.] How to create an array of lists, or structures the most elegant way? > > There have been questions in the past but none too recently...I want to know if the following looks OK to you guys or if there is a better way to create an array of lists: > > # PREAMBLE ... JUST TO GET THINGS GOING > makeList<- function(data, anythingElse) { > rval <- list( data = data, > anythingElse = anythingElse > ) > class(rval) <- "myListOfArbitraryThings" > return(rval) > } > # make up some arbitrary data > payload<- list( as.matrix(cbind(1,1:3)), > 10:15, > data.frame(cbind(x=1, y=1:10), fac=sample(LETTERS[1:3], 10, repl=TRUE)) > ) > > # HERE'S THE ARRAY-CONSTRUCTION PART THAT I WANT CRITIQUED: > n<- 3 # number of lists in the array of lists > v<- vector("list", n) # <--- IS THIS THE BEST WAY TO CREATE AN ARRAY OF LISTS? > # fill the array with essentially arbitrary stuff: > for (i in 1:n) v[[i]]<- makeList(payload[[i]], i)You could use lapply to avoid having to set up the empty list: lapply(1:n, function(i) makeList(payload[[i]], i)) # untested