Extracting nth element from a nested list following strsplit - R

前端 未结 4 1201
醉梦人生
醉梦人生 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:27

    Try this:

    > read.table(text = mydata, sep = "/", as.is = TRUE, fill = TRUE)
       V1 V2 V3
    1 144  4  5
    2 154  2 NA
    3 146  3  5
    4 142 NA NA
    5 143  4 NA
    6 DNB NA NA
    7  90 NA NA
    

    If you want to treat DNB as an NA then add the argument na.strings="DNB" .

    If you really want to use strsplit then try this:

    > do.call(rbind, lapply(strsplit(mydata, "/"), function(x) head(c(x,NA,NA), 3)))
         [,1]  [,2] [,3]
    [1,] "144" "4"  "5" 
    [2,] "154" "2"  NA  
    [3,] "146" "3"  "5" 
    [4,] "142" NA   NA  
    [5,] "143" "4"  NA  
    [6,] "DNB" NA   NA  
    [7,] "90"  NA   NA  
    

    Note: Using alexis_laz's observation that x[i] returns NA if i is not in 1:length(x) the last line of code above could be simplified to:

    t(sapply(strsplit(mydata, "/"), "[", 1:3))
    

提交回复
热议问题