我在R中有一个数据集,如下所示:
x1 x2 x3
1: A Away 2
2: A Home 2
3: B Away 2
4: B Away 1
5: B Home 2
6: B Home 1
7: C Away 1
8: C Home 1
根据列x1和x2中的值,我想删除重复的行。我尝试过以下方法:
df[!duplicated(df[,c('x1', 'x2')]),]
它应该删除第4行和第6行。但遗憾的是它不起作用,因为它返回完全相同的数据,重复项仍然存在于数据集中。我必须使用什么才能删除第4行和第6行?
答案 0 :(得分:5)
我只是这样做:
unique(df, by=c("x1", "x2")) # where df is a data.table
如果您只是查看?unique
,那就很明显了。
PS:考虑到Q中的语法,我想知道你是否了解data.table和data.frame语法之间的基本区别。我建议你先阅读vignettes。
答案 1 :(得分:1)
library("data.table")
setDT(df)[, .SD[1], by = .(x1, x2)]
# x1 x2 x3
# 1: A Away 2
# 2: A Home 2
# 3: B Away 2
# 4: B Home 2
# 5: C Away 1
# 6: C Home 1
答案 2 :(得分:0)
或者您可以使用dplyr
库
library("dplyr")
df <- data.frame(x1 = c("A","A","B","B","B","B","C","C"), x2 = c("Away","Home","Away","Away","Home","Home","Away","Home"), x3 = c(2,2,2,1,2,1,1,1))
distinct(df,x1,x2,.keep_all = TRUE)
# x1 x2 x3
# 1 A Away 2
# 2 A Home 2
# 3 B Away 2
# 4 B Home 2
# 5 C Away 1
# 6 C Home 1