for a simple example: x <- list() x[["a"]] <- list(a=c(1,2,3),b=c(3,4,5)) x[["b"]] <- list(a=c(6,7,8),b=c(9,10,11)) lapply(x,sum) this fails w/ Error in FUN(X[[1L]], ...) : invalid 'type' (list) of argument Just wondering if I have overlooked something obvious. one can also do: lapply(x,lapply,sum) but that assumes that you already know how many levels you have, and that all the levels are consistent. -Whit
This will recursively lapply and may or may not be what you are looking for: rapply(x, sum) On Thu, Dec 11, 2008 at 2:59 PM, Whit Armstrong <armstrong.whit at gmail.com> wrote:> for a simple example: > > x <- list() > x[["a"]] <- list(a=c(1,2,3),b=c(3,4,5)) > x[["b"]] <- list(a=c(6,7,8),b=c(9,10,11)) > > lapply(x,sum) > > > this fails w/ > Error in FUN(X[[1L]], ...) : invalid 'type' (list) of argument > > Just wondering if I have overlooked something obvious. > > one can also do: > > lapply(x,lapply,sum) > > but that assumes that you already know how many levels you have, and > that all the levels are consistent. > > -Whit > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
On Thu, 11 Dec 2008, Whit Armstrong wrote:> for a simple example: > > x <- list() > x[["a"]] <- list(a=c(1,2,3),b=c(3,4,5)) > x[["b"]] <- list(a=c(6,7,8),b=c(9,10,11)) > > lapply(x,sum) > > > this fails w/ > Error in FUN(X[[1L]], ...) : invalid 'type' (list) of argument > > Just wondering if I have overlooked something obvious.rapply? Which is linked from ?lapply (I just checked). Perhaps> rapply(x, sum)a.a a.b b.a b.b 6 12 21 30 or> rapply(x, sum, how="list")$a $a$a [1] 6 .....> > one can also do: > > lapply(x,lapply,sum) > > but that assumes that you already know how many levels you have, and > that all the levels are consistent. > > -Whit > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595