在data.table中创建新列时如何引用整行?

时间:2019-01-24 12:52:02

标签: r data.table

我有一个data.table,其中包含200多个都是二进制的变量。我想在其中创建一个新列,该新列计算每行与参考向量之间的差异:

#Example
dt = data.table(
"V1" = c(1,1,0,1,0,0,0,1,0,1,0,1,1,0,1,0),
"V2" = c(0,1,0,1,0,1,0,0,0,0,1,1,0,0,1,0),
"V3" = c(0,0,0,1,1,1,1,0,1,0,1,0,1,0,1,0),
"V4" = c(1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0),
"V5" = c(1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0)  
)

reference = c(1,1,0,1,0)

我可以使用一个小的for循环来做到这一点,例如

distance = NULL
for(i in 1:nrow(dt)){      
  distance[i] = sum(reference != dt[i,])  
}

但是这有点慢,而且肯定不是最好的方法。我尝试过:

dt[,"distance":= sum(reference != c(V1,V2,V3,V4,V5))]
dt[,"distance":= sum(reference != .SD)]

但是它们都不起作用,因为它们为所有行返回相同的值。另外,我不需要键入所有变量名的解决方案会更好,因为实际的data.table有200多个列

4 个答案:

答案 0 :(得分:7)

您可以将sweep()rowSums一起使用,即

rowSums(sweep(dt, 2, reference) != 0)
 #[1] 2 2 2 2 4 4 3 2 4 3 2 1 3 4 1 3

BENCHMARK

HUGH <- function(dt) {
    dt[, I := .I] 
    distance_by_I <- melt(dt, id.vars = "I")[, .(distance = sum(reference != value)), keyby = "I"]
    return(dt[distance_by_I, on = "I"])
}

Sotos <- function(dt) {
    return(rowSums(sweep(dt, 2, reference) != 0))
}

dt1 <- as.data.table(replicate(5, sample(c(0, 1), 100000, replace = TRUE)))
microbenchmark(HUGH(dt1), Sotos(dt1))

#Unit: milliseconds
#       expr       min        lq      mean   median        uq       max neval cld
#  HUGH(dt1) 112.71936 117.03380 124.05758 121.6537 128.09904 155.68470   100   b
# Sotos(dt1)  23.66799  31.11618  33.84753  32.8598  34.02818  68.75044   100  a 

答案 1 :(得分:7)

另一个:

ref = as.list(reference)
dt[, Reduce(`+`, Map(`!=`, .SD, ref))]

它是如何工作的。因此,我们将.SD中的每个向量列都与ref中的单个对应值进行比较。 !=函数是矢量化的,因此ref的每个元素都被回收以匹配每个矢量的长度。

Map调用返回TRUE / FALSE向量的列表,每列一个。当我们将TRUE / FALSE值相加时,它们将被视为1/0,因此我们只需要将这些列相加即可。这可以通过在第一列和第二列之间传递成对运算符+来实现。然后再次在该计算结果和第三列之间;等等。 Reduce就是这样工作的。

可能更易读
x = dt[, Map(`!=`, .SD, ref)]
Reduce(`+`, x, init = 0L)

可以理解为

  • v = 0
  • 对于x中的每个xi,更新v = v + xi

另请参阅?Map?Reduce


计时。我正在修改基准数据,因为如果OP确实具有0-1数据,则使用整数似乎更明智。另外,由于OP表示有很多列,因此添加了更多列。最后,将休的答案编辑为与其他答案类似:

HUGH <- function(dt, r) {
  dt[, I := .I] 
  res <- melt(dt, id.vars = "I")[, .(distance = sum(r != value)), keyby = "I"]$distance
  dt[, I := NULL]
  res
}

Sotos <- function(dt, r) {
  return(rowSums(sweep(dt, 2, r) != 0))
}

mm <- function(dt, r){
  colSums(t(dt) != r)
}

ff <- function(DT, r){
  DT[, Reduce(`+`, Map(`!=`, .SD, r))]
}

nr = 20000
nc = 500
dt1 <- as.data.table(replicate(nc, sample(0:1, nr, replace = TRUE)))
ref <- rep(as.integer(reference), length.out=nc)
lref = as.list(ref)

identical(HUGH(dt1, ref), ff(dt1, lref)) # integer output
identical(mm(dt1, ref), Sotos(dt1, ref)) # numeric output
all.equal(HUGH(dt1, ref), mm(dt1, ref))  # but they match
# all TRUE

microbenchmark::microbenchmark(times = 3, 
 HUGH(dt1, ref), 
 Sotos(dt1, ref), 
 mm(dt1, ref), 
 ff(dt1, lref)
)

结果:

Unit: milliseconds
            expr      min        lq     mean   median         uq       max neval
  HUGH(dt1, ref) 365.0529 370.05233 378.8826 375.0517  385.79737  396.5430     3
 Sotos(dt1, ref) 871.5693 926.50462 961.5527 981.4400 1006.54437 1031.6488     3
    mm(dt1, ref) 104.5631 121.74086 131.7157 138.9186  145.29197  151.6653     3
   ff(dt1, lref)  87.0800  87.48975  93.1361  87.8995   96.16415  104.4288     3

答案 2 :(得分:3)

这是另一种方式:

mm <- function(dt){
  colSums(t(dt) != reference)
}

mm(dt)
# [1] 2 2 2 2 4 4 3 2 4 3 2 1 3 4 1 3

基准

library(data.table)
dt1 <- as.data.table(replicate(5, sample(c(0, 1), 100000, replace = TRUE)))

identical(Sotos(dt1), mm(dt1))
# [1] TRUE

microbenchmark::microbenchmark(HUGH(dt1), Sotos(dt1), mm(dt1))
# Unit: milliseconds
#       expr       min         lq      mean     median        uq      max neval cld
#  HUGH(dt1) 85.542550 101.339416 129.71317 106.634169 112.66004 473.9380   100   b
# Sotos(dt1) 35.699128  42.677696 125.95430 180.302919 189.34098 377.9523   100   b
#    mm(dt1)  4.604986   7.002416  17.57238   9.819895  12.27015 165.1440   100  a 

答案 3 :(得分:2)

熔化表,然后比较每个组。

override