Remove rows which have all NAs in certain columns

后端 未结 5 1704
面向向阳花
面向向阳花 2020-12-11 08:08

Suppose you have a dataframe with 9 columns. You want to remove cases which have all NAs in columns 5:9. It\'s not at all relevant if there are NAs in columns 1:4.

S

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 08:39

    You can use all with apply to find rows where all values are NA:

    x[!apply(is.na(x[,5:9]), 1, all),]
    

    or negate is.na and test for any:

    x[apply(!is.na(x[,5:9]), 1, any),]
    

    or using rowSums like @RHertel wher you dont need to calculate the number of selected rows:

    x[rowSums(!is.na(x[,5:9])) > 0,]
    

提交回复
热议问题