根据其内容删除行

时间:2019-07-16 13:19:39

标签: r dplyr tidyverse

我正在尝试编写代码,根据其内容删除观察结果。想法是,在初始/初始前,每个观察都必须进行审查。

我的数据框如下:

ID  Type            Registered
P40 Pre-Initial     Yes
P40 Review  
P40 Review  
P42 Initial         Yes
P43 Initial         Yes
P43 Review  
P44 Pre-Initial     Yes
P44 Review  

我的通话代码:

tt <- structure(list(ID = c("P40", "P40", "P40", "P42", "P43", "P43",
                            "P44", "P44"),Type = c("Pre-Initial", "Review", "Review", "Initial", "Initial", "Review", "Pre-Initial", "Review"),
                     Registered = c("Yes", "", "", "Yes", "Yes", "", "Yes", "")),
                class = "data.frame", row.names = c(NA, -8L))

这我想实现:

ID  Type            Registered
P40 Pre-Initial     Yes
P40 Review  
P40 Review  
P43 Initial         Yes
P43 Review  
P44 Pre-Initial     Yes
P44 Review  

这是我到目前为止尝试过的代码,但是没有用。

 tt %>% group_by(ID) %>%
    slice(which(Registered == "Yes" & any(Type != "Review")))
)

2 个答案:

答案 0 :(得分:2)

一种方法是简单地保留多于1行的组,并保留条目Review,即

library(dplyr)

tt %>% 
 group_by(ID) %>% 
 filter(n() > 1 & any(Type == 'Review'))

答案 1 :(得分:1)

  

在初始/初始前,每个观察都必须进行审查。

获取所有Type == "Review"处的索引,并提取最后一个索引,并将其与c("Pre-Initial", "Initial")的索引进行比较,如果索引的any更大,则选择组。

library(dplyr)

tt %>%
  group_by(ID) %>%
  filter(any(tail(which(Type == "Review"), 1) > 
             which(Type %in% c("Pre-Initial", "Initial"))))

#  ID    Type        Registered
#  <chr> <chr>       <chr>     
#1 P40   Pre-Initial Yes       
#2 P40   Review      ""        
#3 P40   Review      ""        
#4 P43   Initial     Yes       
#5 P43   Review      ""        
#6 P44   Pre-Initial Yes       
#7 P44   Review      ""