Lina Bird
Lina Bird

Reputation: 485

Removing rows in which all but one column are empty

with the following code:

data <- rbind(c(1,1,2,3),
          c(1,1, NA, 4), 
          c(1,4,6,7), 
          c(1,NA, NA, NA), 
          c(1,4, 8, NA))

I would like to remove the rows in which columns 2-4 are NA. Is there a way to do this?

Upvotes: 0

Views: 589

Answers (3)

user1317221_G
user1317221_G

Reputation: 15461

another way:

 data[! rowSums(is.na(data[,2:4])) == 3, ]

If it was just columns 2 and 4 then it would be:

data[! rowSums(is.na(data[,c(2,4)])) == 2, ]

Upvotes: 2

thelatemail
thelatemail

Reputation: 93938

To remove the rows where all values in columns 2-4 are NA:

data[apply(data[,2:4],1,function(x) !all(is.na(x))),]

     [,1] [,2] [,3] [,4]
[1,]    1    1    2    3
[2,]    1    1   NA    4
[3,]    1    4    6    7
[4,]    1    4    8   NA

To just exclude the first column from the columns that are checked for NA's, you could use a negative index like:

data[apply(data[,-1],1,function(x) !all(is.na(x))),]

Upvotes: 1

digEmAll
digEmAll

Reputation: 57220

You can do in this way:

filteredData <- data[!is.na(data[,2]) | !is.na(data[,4]),]

> data
     [,1] [,2] [,3] [,4]
[1,]    1    1    2    3
[2,]    1    1   NA    4
[3,]    1    4    6    7
[4,]    1   NA   NA   NA
[5,]    1    4    8   NA

> filteredData
     [,1] [,2] [,3] [,4]
[1,]    1    1    2    3
[2,]    1    1   NA    4
[3,]    1    4    6    7
[4,]    1    4    8   NA

Upvotes: 2

Related Questions