How to get last subelement of every element of a list in R

后端 未结 1 1427
[愿得一人]
[愿得一人] 2020-12-05 22:06

I am trying to get the value of the last element of every subelement of a list in R. The elements of the list are vectors of different length, so the index

相关标签:
1条回答
  • 2020-12-05 22:32

    You can use lapply and tail:

    x <- list(a=1:5, b = 1:10, d = 9:11)
    last_elems <- lapply(x, tail, n = 1L)
    

    As pointed out by Hadd E. Nuff, to obtain a numeric vector instead of a one-element list, vapply is a good choice:

    last_elems <- vapply(x, tail, n = 1L, FUN.VALUE = numeric(1))
    
    0 讨论(0)
提交回复
热议问题