我使用数据集,如果标记为1,我想要删除一行,并且标记为3的ID编号。编辑:标记值只能是:NA,1,2或3。是不同的,如果存在标签1,标签2和标签3,则只能找到三次。
> dat1 = data.frame(id=c(15399,15404,15405,15407,15407,15407,15403), tag=c(NA,NA,1,1,2,3,1))
> dat1
id tag
1 15399 NA
2 15404 NA
3 15405 1
4 15407 1
5 15407 2
6 15407 3
7 15403 1
我需要回复:
> dat1
id tag
1 15399 NA
2 15404 NA
3 15405 1
5 15407 2
6 15407 3
7 15403 1
有人可以帮助我吗?我只想出了如何删除标签为3的所有ID:
> subset(dat1,!dat1$id %in% dat1$id[dat1$tag == 3])
id tag
1 15399 NA
2 15404 NA
3 15405 1
7 15403 1
答案 0 :(得分:1)
我们可以使用data.table
library(data.table)
setDT(dat1)[, .SD[any(tag != 1) & tag !=1 | all(tag==1) |is.na(tag)] , by = id]
# id tag
#1: 15399 NA
#2: 15404 NA
#3: 15405 1
#4: 15407 2
#5: 15407 3
#6: 15403 1
如果条件是要删除包含'标记'作为1还有一个'标签' 3表示特定的' id',然后
setDT(dat1)[, .SD[!(all(c(1,3) %in% tag) & tag == 1)] , id]
# id tag
#1: 15399 NA
#2: 15404 NA
#3: 15405 1
#4: 15407 2
#5: 15407 3
#6: 15403 1
或dplyr
library(dplyr)
dat1 %>%
group_by(id) %>%
filter(any(tag != 1) & tag !=1 | all(tag==1) |is.na(tag))
基于第二个条件
dat1 %>%
group_by(id) %>%
filter(!(all(c(1,3) %in% tag) & tag ==1))
# A tibble: 6 x 2
# Groups: id [5]
# id tag
# <dbl> <dbl>
#1 15399 NA
#2 15404 NA
#3 15405 1
#4 15407 2
#5 15407 3
#6 15403 1
答案 1 :(得分:1)
dat1[!duplicated(dat1$id,fromLast = TRUE)|duplicated(dat1$id)&dat1$tag!="1",]
你可以这样做,但首先你需要按标签订购数据。它不是很漂亮的方式,但它应该工作。
> dat1[!duplicated(dat1$id,fromLast = TRUE)|duplicated(dat1$id)&dat1$tag!="1",]
id tag
1 15399 NA
2 15404 NA
3 15405 1
5 15407 2
6 15407 3
7 15403 1
答案 2 :(得分:0)
dat1 = data.frame(id=c(15399,15404,15405,15407,15407,15407,15403),
tag=c(NA,NA,1,1,2,3,1))#construct the data
dat1_tag3<-dat1[dat1$tag==3,]#keep the rows with tag equals to 3
dat1_tag3<-dat1_tag3[!is.na(dat1_tag3$id),]#remove NA's
dat2remove<-dat1[(dat1$id %in% unique(dat1_tag3$id) & dat1$tag==1),]#find rows that need to be excluded
all<-rbind(dat1,dat2remove)#rbinding the two datasets
all<-all[!(duplicated(all[c("id","tag")]) | duplicated(all[c("id","tag")], fromLast = TRUE)),]#removing duplicates (as pairs)
id tag
1 15399 NA
2 15404 NA
3 15405 1
5 15407 2
6 15407 3
7 15403 1