library(data.table)
iris = data.table(iris)
iris = iris[ , !'Species']
iris[ , (names(iris)) := lapply(.SD, function(x) {
(x - mean(x))/sd(x)
})]
xnm = c('x1', 'x2', 'x3')
setnames(iris, c('y', xnm))
y = iris$y
iris[ , c('r', 'y') := .(y, NULL)]
all_cor = iris[ , sapply(.SD, cor, r), .SDcols = xnm]
active = names(which.max(abs(all_cor)))
path = seq(0, all_cor[active], length.out = 100L)
cor_path = sapply(path, function(beta) {
iris[ , { print(length(.SD))
sapply(.SD, cor, r - beta*get(active))
}, .SDcols = xnm]
})
This may be related to #2036 and/or #1548. Sorry for the over-long example, the last command is the one that matters:
Despite explicitly setting
.SDcols = xnm(i.e.,x1:x3),.SDhas picked upragain (as seen fromnrow(cor_path) == 4L.If we replace
get(active)with its current value (x2), the code works as expected. The fix of #1548 (to setenvir = as.environment(.SD)) doesn't work here.