R list get first item of each element

前端 未结 2 1077
深忆病人
深忆病人 2020-12-28 23:53

This should probably be very easy for someone to answer but I have had no success on finding the answer anywhere.

I am trying to return, from a list in R, the first

相关标签:
2条回答
  • 2020-12-29 00:35

    You can do

     output <- sapply(d, function(x) x[1])
    

    If you don't need the names

     names(output) <- NULL
    
    0 讨论(0)
  • 2020-12-29 00:46

    sapply(d, "[[", 1) should do the trick.

    A bit of explanation:

    sapply: iterates over the elements in the list
    [[: is the subset function. So we are asking sapply to use the subset function on each list element.
    1 : is an argument passed to "[["

    It turns out that "[" or "[[" can be called in a traditional manner which may help to illustrate the point:

    x <- 10:1
    "["(x, 3)
     # [1] 8
    
    0 讨论(0)
提交回复
热议问题