df <- data.frame(id = c(1, 2, 3, 3, 3, 4), gender = c("Male", "Female", "Both", "Male", "Female", "Female"))
ids <- unique(df$id)
> df
id gender
1 1 Male
2 2 Female
3 3 Both
4 3 Male
5 3 Female
6 4 Female
对于每个唯一的 id
,我想确保如果相应的 gender
是 Both
, Male
和 Female
,那么我需要删除对应于 Both
的行 . 换句话说,我想要的输出是:
> df
id gender
1 1 Male
2 2 Female
3 3 Male
4 3 Female
5 4 Female
我试过写一个循环:
- 子集
df
byid
并将每个子集存储到名为sub
的列表中
每个 sub
内
-
,检查性别是否包含"Both","Male"和“女性”
-
如果是,请删除性别=“两者”的行
-
重新组合data.frame
但是,下面的代码并没有真正起作用,并且非常笨重......在 dplyr
中使用 group_by
是一种更简单的方法吗?
sub <- list()
for(i in 1:length(ids)){
sub[[i]] <- subset(df, id %in% ids[i])
if(all(grepl(sub[[i]]$gender, c("Both", "Male", "Female")))){
sub[[i]] <- sub[[i]][-which(sub[[i]]$gender == "Both"), ]
}else sub[[i]] = sub[[i]]
}
2 回答
使用
dplyr
除了tidyverse解决方案,这里有一个使用
lapply
的解决方案: