[R] Split apply combine in data.table

Naresh Gurbuxani n@re@h_gurbux@n| @end|ng |rom hotm@||@com
Wed Feb 4 12:56:37 CET 2026


In this code, I want to create and store an interpolation function for
each date.  It seems that data.table saves the same interpolation
function (for the last date) for all three dates.  How can this problem
be fixed?

Thanks,
Naresh

mydt <- list(data.table(date = as.IDate("2025-01-01"), x = c(1, 2, 3), y = c(3, 4, 5)), data.table(date = as.IDate("2025-01-15"), x = c(1, 2, 3), y = c(9, 8, 7)), data.table(date = as.IDate("2025-01-31"), x = c(1, 2, 3), y = c(10, 12, 9)))
mydt <- rbindlist(mydt)
myapprox <- mydt[, list(yfunc = list(approxfun(x, y, rule = 2))), by =
list(date)]
testdt <- data.table(date = as.IDate(c("2025-01-01", "2025-01-15",
"2025-01-31")), x = 2)
testdt <- merge(testdt, myapprox, by = "date")
testdt[, let(yapprox = yfunc[[1]](x)), by = .I]
testdt <- merge(testdt, mydt, by = c("date", "x"))
testdt
Key: <date, x>
       date     x         yfunc yapprox     y
     <IDat> <num>        <list>   <num> <num>
1: 2025-01-01     2 <function[1]>      12     4
2: 2025-01-15     2 <function[1]>      12     8
3: 2025-01-31     2 <function[1]>      12    12

Using split function, it is possible to get the desired result.
mydtsplit <- split(mydt, f = mydt$date)
splitapprox <- lapply(mydtsplit, function(dt) dt[, approxfun(x, y,
rule = 2)])
newdt <- data.table(date = as.IDate(c("2025-01-01", "2025-01-15",
"2025-01-31")), x = 2)
newdt[, let(yfunc = splitapprox[as.character(date)]), by = .I]
newdt[, let(yapprox = yfunc[[1]](x)), by = .I]
newdt <- merge(newdt, mydt, by = c("date", "x"))
newdt
Key: <date, x>
       date     x         yfunc yapprox     y
     <IDat> <num>        <list>   <num> <num>
1: 2025-01-01     2 <function[1]>       4     4
2: 2025-01-15     2 <function[1]>       8     8
3: 2025-01-31     2 <function[1]>      12    12


	[[alternative HTML version deleted]]



More information about the R-help mailing list