[R] data.table question

Naresh Gurbuxani n@re@h_gurbux@n| @end|ng |rom hotm@||@com
Thu Aug 31 00:15:01 CEST 2023


I want to apply interpolation functions from one data.table to each row
of another data.table.

interp.dt <- data.table(scen = rep(c("a", "b"), c(3, 3)), term = c(1,
20, 60, 1, 32, 72), shock = c(10, 20, 30, 9, 12, 32))

interp.fn <- function(df, x) with(df, approx(term, shock, xout = x)$y)

mydt <- data.table(name = c("xx", "yy", "zz"), term = c(22, 6, 18))

## Does not work
## scen.dt <- CJ(scen = c("a", "b"), mydt)

scen.dt <- lapply(c("a", "b"), function(scenario) {tempdt <- copy(mydt);
tempdt[, scen := scenario]})
scen.dt <- rbindlist(scen.dt)

## Works
interp.fn(interp.dt[scen == "a"], 22)

## Does not work
## scen.dt[, shock := interp.fn(interp.dt[scen == scen], term)]

## Works using data.frame apply
scen.dt[, "shock"] <- apply(scen.dt, 1, function(row) {
interp.fn(interp.dt[scen == row["scen"]], as.numeric(row["term"]))})

Is it possible to get both the above results using native data.table
methods?

Thanks,
Naresh



More information about the R-help mailing list