0

I am curious why data.table's NSE escapes to the surrounding environment even when wrapped in "local()".

library(data.table)

data <- as.data.table(iris)

data[, measure := rep(c('Sepal.Length', 'Sepal.Width'), 75)]

# old way: using get
(data[, check := get(measure)][])

# issue: x is broadcast to entire column if not found in data
data$measure[1] <- 'x'

(data[, check := get(measure)][])

x <- 10

(local(data[, check := get(measure)][], envir = data))

sessionInfo()

R version 3.6.3 (2020-02-29) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale: [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages: [1] stats graphics grDevices utils datasets methods base

other attached packages: [1] data.table_1.14.3

loaded via a namespace (and not attached): [1] compiler_3.6.3 tools_3.6.3

1 Answers1

0

I needed to pass the environment to "get()" rather than wrap the call with "local()"

(data[, check := get(measure, envir = as.environment(.SD))][])

Can also use .SD for convenience