![](/img/trans.png)
[英]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.