[R] Extracting multiple elements from a list
Liaw, Andy
andy_liaw at merck.com
Thu Jan 15 19:57:18 CET 2004
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}}
More information about the R-help
mailing list