我只想从data.table中获取第一行,并按多列进行分组。
这很简单,只需使用一列,例如:
(dt <- data.table(x = c(1, 1, 1, 2),
y = c(1, 1, 2, 2),
z = c(1, 2, 1, 2)))
# x y z
# |1: 1 1 1
# |2: 1 1 2
# |3: 1 2 1
# |4: 2 2 2
dt[!duplicated(x)] # Remove rows 2-3
# x y z
# |1: 1 1 1
# |2: 2 2 2
但是,当尝试基于两列进行删除时,这些方法均无效。即在这种情况下,仅删除第2行:
dt[!duplicated(x, y)] # Keeps only original data set
# x y z
# |1: 1 1 1
# |2: 1 1 2
# |3: 1 2 1
# |4: 2 2 2
dt[!duplicated(list(x, y))] # Same as above
dt[!duplicated(c("x", "y"))] # Same as above
dt[!duplicated(list("x", "y"))] # Same as above
dt[!duplicated(c(x, y))] # Only removes duplicates from first column
# x y z
# |1: 1 1 1
# |2: 2 2 2
除此之外,仅在某些情况下有效:
dt[!duplicated(paste0(x, y))]
# x y z
# |1: 1 1 1
# |2: 1 2 1
# |3: 2 2 2
最佳答案
data.table
为unique
,duplicated
和anyDuplicated
提供S3方法
unique(dt, by = c('x','y'))
会给你你想要的。