[英]R: How to combine rows of a data frame with the same id and take the newest non-NA value?
[英]In R, How do I filter a data frame to only include rows with >=2 non-NA values?
假设我有一个数据框
Grp1 Grp2 Grp3
Trt1 NA 1 NA
Trt2 2 3 NA
Trt3 4 NA 5
我想将其过滤为仅包含非 NA 值的数量大于某些总数(在本例中为 2)的行。 所以对于这个例子,我想要一个结果:
Grp1 Grp2 Grp3
Trt2 2 3 NA
Trt3 4 NA 5
您可以使用rowSums()
和is.na()
来过滤数据框。 这将强制您用于过滤到矩阵中的值(因此它可能会遇到非常大的数据帧问题),但它应该可以解决问题。
df1[rowSums(!is.na(df1)) >= 2, ]
Grp1 Grp2 Grp3
Trt2 2 3 NA
Trt3 4 NA 5
资料:
df1 <- read.table(header = T, text = " Grp1 Grp2 Grp3
Trt1 NA 1 NA
Trt2 2 3 NA
Trt3 4 NA 5")
你可以这样做:
count_na <- apply(data, 1, function(x) sum(is.na(x)))
data[count_na < 2,]
样本数据:
col1 col2 col3
1 1 1 NA
2 NA NA 2
3 NA 3 3
新输出:
col1 col2 col3
1 1 1 NA
3 NA 3 3
另外一个选择:
data[apply(data,1,function(x) sum(!is.na(x)) >= 2),]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.