首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >R:使用dplyr删除data.frame中的某些行

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

Stack Overflow用户
提问于 2018-06-11 07:26:08
回答 1查看 15.7K关注 0票数 5
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如果对于给定的IDGender的所有3个元素都存在("Both“、"Male”和"Female";这些是Gender可以接受的不同值,其他值是不可能的),相应的行将具有Gender == Both。然后,我将删除该行。

但是,似乎我将A = F赋给了第一行,即使它的Gender只是"Both",而不是“Both”、"Male“和"Female"?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50788898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档