Re: Split apply combine in data.table
Ivan Krylov via R-help <[email protected]> Wed, 4 Feb 2026 16:10:52 +0300
| Newsgroups | gmane.comp.lang.r.general |
|---|---|
| Message-ID | <20260204161052.12f02316@arachnoid> |
В Wed, 4 Feb 2026 11:56:37 +0000 Naresh Gurbuxani <[email protected]> пишет: > 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