5

I want to remove some rows which contain missing value in specific columns. for example,

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   NA    3    3   NA    3
[2,]   NA   NA   NA   NA   NA    1
[3,]   NA    2   NA   NA    1    1
[4,]    2    3    1    3    2    1
[5,]   NA   NA   NA   NA   NA    2
[6,]    1    1    3    1    2    3

Now I want to remove some rows containing all missing value from columns 1 to column 5. in this case, I should remove row 2 and row 5. Thus, the dataframe became

   [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   NA    3    3   NA    3
[2,]   NA    2   NA   NA    1    1
[3,]    2    3    1    3    2    1
[4,]    1    1    3    1    2    3

How to deal with that? Thanks in advance.

user2702330
  • 311
  • 3
  • 10

2 Answers2

3

Another variation using rowSums:

M[!rowSums(is.na(M[ , 1:5])) == 5, ]

#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    2   NA    3    3   NA    3
# [2,]   NA    2   NA   NA    1    1
# [3,]    2    3    1    3    2    1
# [4,]    1    1    3    1    2    3

To get a better feeling for what's going on, it is often useful to work your way from the innermost function and add functions to it step by step, something like:

is.na(M[ , 1:5]) # or even just M[ , 1:5]... 
rowSums(is.na(M[ , 1:5]))
rowSums(is.na(M[ , 1:5])) == 5
!rowSums(is.na(M[ , 1:5])) == 5
Henrik
  • 65,555
  • 14
  • 143
  • 159
2

First, I recreate your data and store them as M

M <- matrix(c(2, NA,3,3,NA,3,NA,NA,NA,NA,NA,1,NA,2,NA,NA,1,1,2,3,1,3,2,1,NA,NA,NA,NA,NA,2,1,1,3,1,2,3), ncol=6, byrow=T)

Now the next bit can be bit harder to follow:

First I find out, which rows fulfill the condition, that there are NA values in columns 1 to 5.

apply(M[,1:5],1,function(x) {all(is.na(x))} )
[1] FALSE  TRUE FALSE FALSE  TRUE FALSE

And then I select the other rows (I put ! in front of the line above)

M[!apply(M[,1:5],1,function(x) {all(is.na(x))} ),]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   NA    3    3   NA    3
[2,]   NA    2   NA   NA    1    1
[3,]    2    3    1    3    2    1
[4,]    1    1    3    1    2    3
Zbynek
  • 5,673
  • 6
  • 30
  • 52