1

Suppose I have a list of vectors (none of them is empty; they may be of various lengths).

How can I generate a list of elements from the ends (say) of the vectors?

For example, if my list contains 3 elements, 1:10, 2:9 and c(3,5), then the output list should be the list containing 10, 9 and 5.

In the simpler case, where all vectors are of the same length (5, say), I tried to first make the list a data.frame using as.data.frame. The problem is that my list is huge (about 1 million vectors), and as.data.frame takes ages. I thought about optimization, perhaps using this answer, but anyway I think that it results a wrong data structure - instead of having 5 columns with 1 million values each, it creates a data.frame with a million columns.

So I should probably look somewhere else. Any ideas?

Community
  • 1
  • 1
Bach
  • 6,145
  • 7
  • 36
  • 61

2 Answers2

3

If x is a list of atomic vectors, apply:

 sapply(x, function(elem) elem[length(elem)])
gagolews
  • 12,836
  • 2
  • 50
  • 75
3

Use tail:

> sapply(list(1:10,2:9,c(3,5)),tail,1)
[1] 10  9  5

And @Bach is correct about speed. While tail is terse, it is slow:

set.seed(1)
a <- list()
for(i in 1:1e3)
    a[[i]] <- sample(1:100, sample(1:100), TRUE)

library("microbenchmark")
microbenchmark(sapply(a,tail,1), sapply(a, function(elem) elem[length(elem)]))
# Unit: milliseconds
#                                          expr       min        lq    median        uq       max neval
#                            sapply(a, tail, 1) 22.998933 24.790584 26.103241 27.797130 79.489209   100
#  sapply(a, function(elem) elem[length(elem)])  1.546477  1.787224  1.951572  2.137856  6.106236   100
Thomas
  • 43,637
  • 12
  • 109
  • 140
  • I think that @gagolews's solution is by far faster (not sure, though). – Bach Apr 29 '14 at 19:36
  • If speed is a concern neither solution should use `sapply`. Instead, `vapply` with an expected `numeric(1)`. – flodel Apr 29 '14 at 20:05
  • @flodel Good point. What do you have in mind instead of `sapply`? There is a gain from doing `unlist(lapply(...))` here, but are you thinking something else? – Thomas Apr 29 '14 at 20:13