Combining more than 2 columns by removing NA's in R

前端 未结 3 2169
说谎
说谎 2020-12-06 07:28

At first sight this seems a duplicate of Combine/merge columns while avoiding NA? but in fact it isn\'t. I am dealing sometimes with more than two columns instead of just tw

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 08:13

    You can use apply and na.exclude

    DF
    ##   V1 V2 V3 V4 V5
    ## 1  1 NA NA 13 NA
    ## 2 NA NA 10 NA 18
    ## 3 NA  7 NA 15 NA
    ## 4  4 NA NA 16 NA
    
    t(apply(DF, 1, na.exclude))
    ##      [,1] [,2]
    ## [1,]    1   13
    ## [2,]   10   18
    ## [3,]    7   15
    ## [4,]    4   16
    

    If you want to keep the dimensions of the data.frame same, you can use sort with na.last=TRUE instead. This will also take care of cases where you have unequal number of values in different rows.

    t(apply(DF, 1, sort, na.last = T))
    ##      [,1] [,2] [,3] [,4] [,5]
    ## [1,]    1   13   NA   NA   NA
    ## [2,]   10   18   NA   NA   NA
    ## [3,]    7   15   NA   NA   NA
    ## [4,]    4   16   NA   NA   NA
    

提交回复
热议问题