4

我想从 data.table 中获取唯一的行,给定列的子集和i. 最好的方法是什么?(在计算速度和简短或可读语法方面的“最佳”)

set.seed(1)
jk <- data.table(c1 = sample(letters,60,replace = TRUE), 
                 c2 = sample(c(TRUE,FALSE),60, replace = TRUE), 
                 c3 = sample(letters,60, replace = TRUE),
                 c4 = sample.int(10,60, replace = TRUE)
                 )

假设我想找到10c1c2where c4is 10 的唯一组合。我可以想到几种方法来做到这一点,但不确定什么是最佳的。要提取的列是否带键也很重要。

## works but gives an extra column
jk[c4 >= 10, TRUE, keyby = list(c1,c2)]
## this removes extra column
jk[c4 >= 10, TRUE, keyby = list(c1,c2)][,V1 := NULL]

## this seems like it could work
## but no j-expression with a keyby throws an error
jk[c4 >= 10, , keyby = list(c1,c2)]

## using unique with .SD
jk[c4 >= 10, unique(.SD), .SDcols = c("c1","c2")]
4

1 回答 1

4

至少对我来说,最直接的方法是unique(jk[c4 >= 10, list(c1, c2)])@Justin 建议的,或者unique(jk[c4 >= 10, c("c1", "c2")]). 后者是迄今为止四个建议中最快的,至少在我的笔记本电脑上是这样:

microbenchmark(
a=jk[c4 >= 10, list(c1,c2), keyby = list(c1,c2)][,c("c1","c2")],
b=jk[c4 >= 10, unique(.SD), .SDcols = c("c1","c2")],
c=unique(jk[c4>=10,list(c1,c2)]),
d=unique(jk[c4>=10,c("c1","c2")])
)

Unit: microseconds
 expr      min       lq    median        uq      max neval
    a 1378.742 1456.676 1494.9380 1531.1395 2515.796   100
    b  906.404  943.072  963.7790  997.4930 3805.846   100
    c 1167.125 1201.988 1232.3500 1272.2250 2077.047   100
    d  627.768  653.314  669.8625  683.8045  739.808   100
于 2013-10-24T21:00:38.667 回答