df <- data.frame(id = c(1, 1, 1, 2, 2),
gender = c("Female", "Female", "Male", "Female", "Male"),
variant = c("a", "b", "c", "d", "e"))
> df
id gender variant
1 1 Female a
2 1 Female b
3 1 Male c
4 2 Female d
5 2 Male e
我想根据以下内容删除 data.frame 中的重复行gender
我的数据集中的列。我知道有人问过类似的问题(here)但这里的区别是我想删除数据集的每个子集中的重复行,其中每个子集由唯一的定义id
.
我想要的结果是这样的:
id gender variant
1 1 Female a
3 1 Male c
4 2 Female d
5 2 Male e
我已经尝试过以下方法并且它有效,但我想知道是否有更干净、更有效的方法来做到这一点?
out = list()
for(i in 1:2){
df2 <- subset(df, id == i)
out[[i]] <- df2[!duplicated(df2$gender), ]
}
do.call(rbind.data.frame, out)