我们可以尝试。
system.time(DT[, height:= NA^(!height)*height])
原帖中的代码
system.time(DT[height == 0, height := NA])
base R
选项应该更快。
system.time(DT$height[DT$height == 0] <- NA)
并且使用 is.na
方法
system.time(is.na(DT$height) <- DT$height == 0)
@DavidArenburg的建议
system.time(set(DT, i = which(DT[["height"]] == 0), j = "height", value = NA))
注意:所有这些基准测试都是在每次运行之前新创建数据集,以提供一些无偏的基准测试。我可以使用 microbenchmark
,但每次运行中会有一些偏差,因为第一次运行时会发生分配。
使用更大的数据集
set.seed(24)
DT <- data.table(id = 1:1e8,
height = sample(c(0, 100:240), 1e8, replace = TRUE))
system.time(DT[, height:= NA^(!height)*height])
system.time(set(DT, i = which(DT[["height"]] == 0), j = "height", value = NA))
数据
set.seed(24)
DT <- data.table(id = 1:1e7,
height = sample(c(0, 100:240), 1e7, replace = TRUE))
DT[height == 0, height := NA]
运行缓慢吗? - David Arenburgset(DT, i = which(DT[["height"]] == 0), j = "height", value = NA)
我猜。 - David Arenburgset(DT, which(DT$height==0), "height", value = NA)
。 - s_baldur