繁体   English   中英

R:使用dplyr删除data.frame中的某些行

[英]R: using dplyr to remove certain rows in the data.frame

dat <- data.frame(ID = c(1, 2, 2, 2), Gender = c("Both", "Both", "Male", "Female"))
> dat
  ID Gender
1  1   Both
2  2   Both
3  2   Male
4  2 Female

对于每一个ID,如果性别是BothMaleFemale ,我想与删除行Both 也就是说,我想要的数据是这样的:

  ID Gender
1  1   Both
2  2   Male
3  2 Female

我尝试通过使用下面的代码来做到这一点:

library(dplyr)
> dat %>% 
  group_by(ID) %>% 
  mutate(A = ifelse(length(unique(Gender)) >= 3 & Gender == 'Both', F, T)) %>% 
  filter(A) %>% 
  select(-A)

# A tibble: 2 x 2
# Groups:   ID [1]
     ID Gender
  <dbl> <fctr>
1     2   Male
2     2 Female

我声明了一个虚拟变量称为A ,其中A = F ,如果对于给定的ID ,在所有3个元素Gender存在(“两者”,“男性”和“女性”,这些都是不同的值即Gender可以采取,则不能再使用其他值),并且相应的行具有Gender == Both 然后,我将删除该行。

但是,即使我的Gender仅是“两个”,但不是“两个”,“男性”和“女性”,似乎我还是在第一行中分配了A = F

按“ ID”分组后,创建一个逻辑条件,其中“性别”不是“两个”,并且“性别”中distinct元素的长度为3,即“男性”,“女性”,“两个”(如操作说明所述) (没有其他值)或( | )如果元素数仅为1

dat %>% 
  group_by(ID) %>% 
  filter((Gender != "Both" & n_distinct(Gender)==3)| n() ==1 )
# A tibble: 3 x 2
# Groups:   ID [2]
#    ID Gender
#  <dbl> <fct> 
#1     1 Both  
#2     2 Male  
#3     2 Female

或另一个选择是

dat %>%
   group_by(ID) %>% 
   filter(Gender %in% c("Male", "Female")| n() == 1)
# A tibble: 3 x 2
# Groups:   ID [2]
#     ID Gender
#  <dbl> <fct> 
#1     1 Both  
#2     2 Male  
#3     2 Female

从底数R开始,使用ave

dat[!(ave(dat$Gender,dat$ID,FUN=function(x) length(unique(x)))!='1'&(dat$Gender=='Both')),]
  ID Gender
1  1   Both
3  2   Male
4  2 Female

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM