我一直在循环中使用get()通过i引用其他多个列来操纵j列。
我想知道是否有更快/更有效的方法?有性能方面的考虑吗?
这是我想到的操作类型的最小示例:
require(data.table) # version 1.12.8
dt = data.table(v1=c(1,2,NA),v2=c(0,0,1),v3=c(0,0,0))
for (i in 1:2){
dt[ is.na(get(paste0('v',i))), (paste0('v',i)):= get(paste0('v',i+1))+2 ][]
}
我这样做的实际表要大得多(〜5 mio行,〜300列)。
我将不胜感激。
We can use
set
which would assign in placeYes your
for
loop slows you down considerably. Even a simplelapply
(and there's probably more elegant ways to do), brings you significant performance gains:Since you update by reference your
data.table
, you will get the same output in both cases. To extract the result, you can take the last element of your output list可能有一种更优雅的方法,但是对于只花几秒钟编程的东西,将其平均计算时间除以10就是一个很好的结果;)