Reputation: 485
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
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
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
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