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

标签 r dataframe dplyr

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,如果 Gender 是 Both , Male , 和 Female ,我想用 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 , Gender 的所有 3 个元素存在(“Both”、“Male”和“Female”;这些是 Gender 可以采用的不同值,其他值都不可能)并且对应的行有 Gender == Both .然后我将删除该行。

但是,似乎我正在分配 A = F到第一行,即使它是 Gender只是“Both”,而不是“Both”、“Male”和“Female”?

最佳答案

按'ID'分组后,创建一个逻辑条件,其中'Gender'不是'Both',长度为distinct 'Gender' 中的元素为 3,即 'Male'、'Female'、'Both'(如 OP 所述,没有其他值)或 ( | ) 如果元素数仅为 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:使用 dplyr 删除 data.frame 中的某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50788898/

相关文章:

r - 无法在 R 中安装 rgbif 包

r - is.integer() 在重新赋值中的行为

r - 计算特定组的相对频率

r - R中的队列分析

r - 行之间的条件时间差。研发&dplyr/data.table

r - 在 R 中的 roc 图上按组添加 AUC

python - 具有最小值、最大值、平均值和标准差的箱线图

python - 如何从 Dataframe 指定日期时间中的年、月、日?

python - 在 Pandas 中使用 .map 从字典创建列时省略大括号

Python使用列表中的项目迭代创建过滤器表达式