Extracting nth element from a nested list following strsplit - R

前端 未结 4 1058
醉梦人生
醉梦人生 2021-01-02 17:09

I\'ve been trying to understand how to deal with the output of strsplit a bit better. I often have data such as this that I wish to split:

myd         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 17:31

    You can assign the length inside sapply, resulting in NA where the current length is shorter than the assigned length.

    s <- strsplit(mydata, "/")
    sapply(s, function(x) { length(x) <- 3; x[2] })
    # [1] "4" "2" "3" NA  "4" NA  NA 
    

    Then you can add a second indexing argument with mapply

    m <- max(sapply(s, length))
    mapply(function(x, y, z) { length(x) <- z; x[y] }, s, 2, m)
    # [1] "4" "2" "3" NA  "4" NA  NA 
    

提交回复
热议问题