[R] Split apply combine in data.table
Ivan Krylov
|kry|ov @end|ng |rom d|@root@org
Wed Feb 4 14:10:52 CET 2026
В Wed, 4 Feb 2026 11:56:37 +0000
Naresh Gurbuxani <naresh_gurbuxani using hotmail.com> пишет:
> myapprox <- mydt[, list(yfunc = list(approxfun(x, y, rule = 2))), by =
> list(date)]
The grouping operations in data.table reuse the same objects 'x', 'y'
with different contents when evaluating the expression for different
groups. As a result, the same objects end up being captured by
approxfun() for different groups:
myapprox$yfunc |> sapply(\(.) environment(.)$x |> address()) |> unique()
# [1] "0x562038fdbd88" # <-- only one address instead of three
Ideally, data.table should notice that its internal object is captured
instead of blindly reusing it for the next group, but it doesn't
currently do that. As a workaround, you can copy the otherwise-shared
objects explicitly:
myapprox <- mydt[,
.(yfunc = .(approxfun(copy(x), copy(y), rule = 2))),
by = .(date)
]
myapprox$yfunc |> sapply(\(.) environment(.)$x |> address()) |> unique()
# [1] "0x562039b93238" "0x562039b92d38" "0x562039b92888"
--
Best regards,
Ivan
More information about the R-help
mailing list