Skip to content
Prev 58308 / 398502 Next

make apply() return a list

for()-loops aren't so bad.  Look inside the code of apply() and see what it 
uses!  The important thing is that you use vectorized functions to 
manipulate vectors.  It's often fine to use for-loops to manipulate the 
rows or columns of a matrix, but once you've extracted a row or a column, 
then use a vectorized function to manipulate that data.

In any case, one way to get apply() to return a list is to wrap the result 
from the subfunction inside a list, e.g.:

 > x <- apply(matrix(1:6,2), 1, function(x) list((c(mean=mean(x), sd=sd(x)))))
 > x
[[1]]
[[1]][[1]]
mean   sd
    3    2


[[2]]
[[2]][[1]]
mean   sd
    4    2


 > # to remove the extra level of listing here, do:
 > lapply(x, "[[", 1)
[[1]]
mean   sd
    3    2

[[2]]
mean   sd
    4    2

 >
At Monday 11:37 AM 11/1/2004, Arne Henningsen wrote: