Select first element of nested list

后端 未结 5 1272
心在旅途
心在旅途 2020-12-02 06:21

Let\'s say I have a list like this:

x = list(list(1,2), list(3,4), list(5,6))

I would like a list that contains only the first elements of

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 06:56

    For your example list you can just do:

    unlist(x)[ c(TRUE,FALSE) ]
    

    but that depends on each sublist having exactly 2 elements.

    If there are different numbers of elements then you could first do an sapply to calculate the lengths, then compute the corresponding 1st element positions (see cumsum), then select those values from the unlisted list. But by that time the accepted answer is probably much simpler.

    If all the sublists have the same length (but could be different from 2) then you could do something like:

    do.call( rbind, x)[,1]
    

    or some other cast to a common object. But I doubt that this would be as efficient as the lapply approach.

提交回复
热议问题