Extracting multiple elements from a list
[] works on a list and extracts multiple elements. However, that is not
it seems what you want, rather, unions of elements of elements of lists.
That is a pretty unusual need, and perhaps you could explain you you need
it.
Andy's solution still need something like
do.call("c", lapply(alist, function(x) x$vec))
but then it *is* unions of elements of elements of lists.
On Thu, 15 Jan 2004, Liaw, Andy wrote:
Aren't sapply()/lapply() sufficient for this?
sapply(alist, function(x) x$vec)
[,1] [,2] [1,] 1 5 [2,] 2 6 [3,] 3 7 [4,] 4 8
lapply(alist, function(x) x$vec)
[[1]] [1] 1 2 3 4 [[2]] [1] 5 6 7 8 HTH, Andy
From: Waichler, Scott R
For a long time I've wanted a way to conveniently extract
multiple elements
from a list, which [[ doesn't allow. Can anyone suggest an efficient
function to do this? Wouldn't it be a sensible addition to R?
For example,
alist <- list()
alist[[1]] <- list()
alist[[1]]$name <- "first"
alist[[1]]$vec <- 1:4
alist[[2]] <- list()
alist[[2]]$name <- "second"
alist[[2]]$vec <- 5:8
both.vec <- c(alist[[1]]$vec, alist[[2]]$vec)
Can I get both.vec without c() or an explicit loop?
and
new.names <- c("one", "two")
alist[[1]]$name <- new.names[1]
alist[[2]]$name <- new.names[2]
Could I assign the new values in a quasi-vectorized way?
Thanks,
Scott Waichler
Pacific Northwest National Laboratory
Richland, WA USA
------------------------------------------------------------------------------
Notice: This e-mail message, together with any attachments,...{{dropped}}
______________________________________________ R-help at stat.math.ethz.ch mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
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