[英]In R, How do I filter a data frame to only include rows with >=2 non-NA values?
Suppose I have a dataframe假设我有一个数据框
Grp1 Grp2 Grp3
Trt1 NA 1 NA
Trt2 2 3 NA
Trt3 4 NA 5
I'd like to filter this down to only include rows where the number of non-NA values is greater than some total (in this case 2).我想将其过滤为仅包含非 NA 值的数量大于某些总数(在本例中为 2)的行。 So for this example I would like a result:
所以对于这个例子,我想要一个结果:
Grp1 Grp2 Grp3
Trt2 2 3 NA
Trt3 4 NA 5
You could use rowSums()
and is.na()
to filter the dataframe.您可以使用
rowSums()
和is.na()
来过滤数据框。 This will coerce the values you are using to filter into a matrix (so it may have issues with very large dataframes), but it should do the trick.这将强制您用于过滤到矩阵中的值(因此它可能会遇到非常大的数据帧问题),但它应该可以解决问题。
df1[rowSums(!is.na(df1)) >= 2, ]
Grp1 Grp2 Grp3
Trt2 2 3 NA
Trt3 4 NA 5
Data :资料:
df1 <- read.table(header = T, text = " Grp1 Grp2 Grp3
Trt1 NA 1 NA
Trt2 2 3 NA
Trt3 4 NA 5")
You can do it this way:你可以这样做:
count_na <- apply(data, 1, function(x) sum(is.na(x)))
data[count_na < 2,]
sample data:样本数据:
col1 col2 col3
1 1 1 NA
2 NA NA 2
3 NA 3 3
new output:新输出:
col1 col2 col3
1 1 1 NA
3 NA 3 3
Another option:另外一个选择:
data[apply(data,1,function(x) sum(!is.na(x)) >= 2),]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.