Remove empty zero length rows in list with R

后端 未结 1 682
日久生厌
日久生厌 2020-12-17 20:46

I have list of dataframes and some are empty, how can I remove these?

$`S566X7221`
[1] V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11 V12 V13 V14 V15 V16 V17 V1         


        
相关标签:
1条回答
  • 2020-12-17 21:09

    You're close. But you want nrow, not length (which is actually the number of columns in a data.frame).

    x <- list(data.frame(A=numeric(),B=numeric()), data.frame(A=1:3, B=4:6), data.frame(A=1,B=2))
    x[sapply(x, nrow)>0]
    

    Before:

    > x
    [[1]]
    [1] A B
    <0 rows> (or 0-length row.names)
    
    [[2]]
      A B
    1 1 4
    2 2 5
    3 3 6
    
    [[3]]
      A B
    1 1 2
    

    After:

    > x[sapply(x, nrow)>0]
    [[1]]
      A B
    1 1 4
    2 2 5
    3 3 6
    
    [[2]]
      A B
    1 1 2
    
    0 讨论(0)
提交回复
热议问题