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?
我想删除列2-4为NA的行。有没有办法做到这一点?
3 个解决方案
#1
2
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
#2
2
another way:
data[! rowSums(is.na(data[,2:4])) == 3, ]
If it was just columns 2 and 4 then it would be:
如果只是第2列和第4列那么它将是:
data[! rowSums(is.na(data[,c(2,4)])) == 2, ]
#3
1
To remove the rows where all values in columns 2-4 are NA
:
要删除第2-4列中所有值为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:
要从检查NA的列中排除第一列,您可以使用负索引,如:
data[apply(data[,-1],1,function(x) !all(is.na(x))),]
#1
2
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
#2
2
another way:
data[! rowSums(is.na(data[,2:4])) == 3, ]
If it was just columns 2 and 4 then it would be:
如果只是第2列和第4列那么它将是:
data[! rowSums(is.na(data[,c(2,4)])) == 2, ]
#3
1
To remove the rows where all values in columns 2-4 are NA
:
要删除第2-4列中所有值为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:
要从检查NA的列中排除第一列,您可以使用负索引,如:
data[apply(data[,-1],1,function(x) !all(is.na(x))),]