Skip to content

Extracting multiple elements from a list

2 messages · Waichler, Scott R, Julian Taylor

#
Brian described well the operation I would like to do.
I'm not familiar with do.call() but I'll work on that.
Yes, ideally I would like to access values throughout a list object
with fully implict indexing, such as the invalid "alist[[1:2]]$vec[c(2, 4)]".
Notice I was hoping to subset anywhere in the data structure.
Since I can't do this subsetting with indexing directly, I was looking for
handy (and hopefully fast) functions that could be defined
generically and then called with arguments.  The use of sapply()
and lapply() with function(i) seem promising, but do not quite
cover the functionality I was looking for.

The basic application of sapply() suggested by Andy 
is fine but I can't access part of the second-level list, only the whole
vector.  Roger's use of sapply() 

 as.vector(sapply(alist, "[[", "vec"))

is a nice way to get the whole vector also, and I appreciate learning 
that syntax.  The correction by Roger for his use of lapply() still isn't 
right though (see below).

alist <- lapply(seq(along = alist), function(i) {
                 alist[[i]]$name <- new.names[i]
                 alist
          })

I desire:
[[1]]
[[1]]$name
[1] "one"

[[1]]$vec
[1] 1 2 3 4


[[2]]
[[2]]$name
[1] "two"

[[2]]$vec
[1] 5 6 7 8

Roger's use of lapply() give:
[[1]]
[[1]][[1]]
[[1]][[1]]$name
[1] "one"

[[1]][[1]]$vec
[1] 1 2 3 4


[[1]][[2]]
[[1]][[2]]$name
[1] "two"

[[1]][[2]]$vec
[1] 5 6 7 8



[[2]]
[[2]][[1]]
[[2]][[1]]$name
[1] "one"

[[2]][[1]]$vec
[1] 1 2 3 4


[[2]][[2]]
[[2]][[2]]$name
[1] "two"

[[2]][[2]]$vec
[1] 5 6 7 8
#
"Waichler, Scott R" wrote:
The functions sapply() and lapply() have more generality that has been
overlooked in this thread.

This will answer your first question.
[1] 2 4 6 8
    
hth,
Julian