【发布时间】:2019-09-09 16:13:55
【问题描述】:
我想遍历 data.table 并应用一个函数,该函数需要 data.table 中另一列的信息,有时甚至是多个...
我们以mtcars为例
我觉得您可以坚持使用 .SD 方式,但可以提供额外的参数并提高效率...
require(data.table)
dt = data.table(mtcars)
#looping through columns of mtcars...
cols = c('mpg', 'hp', 'disp')
dt[,lapply(.SD, function(x) x/mean(x)), .SDcols=cols]
# But actually I want to devide x by the mean of x where am==1
# Now I am doing this...
specificMean= function(DT) {
x = DT$feature
xAM = DT[AM==1]$feature
MEAN = mean(xAM, na.rm=TRUE)
x = x/MEAN
return(x)
}
dt[,(cols):=lapply(cols, function(x) specificMean(data.table(feature=get(x), AM=am))), .SDcols=cols]
print(dt)
我觉得这要慢得多,因为它在每次迭代中执行 data.table() 函数...
矢量化解决方案会很好..
【问题讨论】:
标签: r performance data.table iteration vectorization