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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With