data.table | faster row-wise recursive update within group
问题 I have to do the following recursive row-by-row operation to obtain z : myfun = function (xb, a, b) { z = NULL for (t in 1:length(xb)) { if (t >= 2) { a[t] = b[t-1] + xb[t] } z[t] = rnorm(1, mean = a[t]) b[t] = a[t] + z[t] } return(z) } set.seed(1) n_smpl = 1e6 ni = 5 id = rep(1:n_smpl, each = ni) smpl = data.table(id) smpl[, time := 1:.N, by = id] a_init = 1; b_init = 1 smpl[, ':=' (a = a_init, b = b_init)] smpl[, xb := (1:.N)*id, by = id] smpl[, z := myfun(xb, a, b), by = id] I would like