我有一個資料框:
bigDf <- data.frame(sampleType = c("D","D","D","P1", "P2","D","P3","D","P1")
,patient= c("x17","x17","x18","x18","x18","x19","x19","x20","x20"))
它看起來像這樣:
> bigDf
sampleType patient
1 D x17
2 D x17
3 D x18
4 P1 x18
5 P2 x18
6 D x19
7 P3 x19
8 D x20
9 P1 x20
我只想保留來自patients同時具有Dand的行P1 sampleTypes,并拒絕patients具有其中一個或不具有這些的行,以及具有除Dand以外的樣本型別的行P1(即使我保留其他行來自相同的patient)。
我想要的輸出是這樣的:
> outputDf
sampleType patient
1 D x18
2 P1 x18
3 D x20
4 P1 x20
我知道我必須group_by(patient)這樣做,但不知道如果存在另一行,如何只保留一排。
編輯:我bigDF稍微改變了一下以顯示比P2 sampleType可能不得不被拒絕的更多。
uj5u.com熱心網友回復:
library(dplyr)
bigDf %>%
group_by(patient) %>%
filter(all(c("D", "P1") %in% sampleType),
!sampleType %in% c("P2", "P3")) %>%
ungroup
-輸出
# A tibble: 4 × 2
sampleType patient
<chr> <chr>
1 D x18
2 P1 x18
3 D x20
4 P1 x20
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529445.html
標籤:rdplyr筛选
下一篇:二維陣列中的元素總和
