'R: Running the same data.table code inside and outside a function yields different result
I wrote code which works, and then I put the same code inside a function and it gives nearly identical except for 2 columns where it transforms numbers into NAs. Generally I post a stylized example which has the same behavior but I haven't been able to replicate the behavior. I'm aware that this is unhelpful but I'm still hoping some of you might be able to help.
Here is the code for what I think is the identical code, just stylized:
test <- data.table(v = ceiling(runif(20, 0, 4)), g = ceiling(runif(20, 0, 2)), b = rbinom(20, 1, 0.01), w = rnorm(20))
setorder(test, g, v, b)
test1 <- test
test2 <- test
test1[, (paste0("n", 1:4)) := lapply(1:4, function(x) sum(v == x) > 2), by = g]
test1[, (paste0("boo", 1:4)) := lapply(1:4, function(x){
mean(w[b == 1 & get(paste0("n", x)) == TRUE]) - mean(w[b == 0 & get(paste0("n", x)) == TRUE])}), by = g]
test1[, lapply(.SD, function(x) x[1]), by = g, .SDcols = c("v", "g", paste0("boo", 1:4))]
bla <- function(dat){
dat[, (paste0("n", 1:4)) := lapply(1:4, function(x) sum(v == x) > 2), by = g]
dat[, (paste0("boo", 1:4)) := lapply(1:4, function(x){
mean(w[b == 1 & get(paste0("n", x)) == TRUE]) - mean(w[b == 0 & get(paste0("n", x)) == TRUE])}), by = g]
fin <- dat[, lapply(.SD, function(x) x[1]), by = g, .SDcols = c("v", "g", paste0("boo", 1:4))]
}
tmp <- bla(test2)
tmp
When I do this in my actual code, whenever the boo columns are actually numbers and not NaNs, I get the numbers when I run the code inside the function directly, but when I run it through the function all the numbers are replaced by NAs (and the NaNs stay NaNs).
At first I though it might have something to do with get behaving strangely, so I tried eval(as.name()) as well as a version with .SD[b == 0 & get(paste0("n", x)) == TRUE]$w.
But none of these fix the problem! Again I'm sorry for not having a code which reproduces the error, but I have tried and I'm really out of ideas now ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
