Provided this example, I would like to calculate the sum of values inside lists in variable b according to the length determined by variable a.
Please consider the following reproducible example:
require(data.table)
dt <- data.table(a = 1:4)
dt[, b:= .(list(1:6))]
Now I want to calculate something like this:
dt[, c:= sum(b[[1]][1:a])]
Of course this results in a warning message and a result different from expected.
I also tried to use apply, but it returns an error because of an attempted NA/NaN operation:
dt[, c := apply(.SD, 1, function(x) sum(x[1][[1]][1:x[2]]))]
My expected result is:
> dt
a b c
1: 1 1,2,3,4,5,6 1
2: 2 1,2,3,4,5,6 3
3: 3 1,2,3,4,5,6 6
4: 4 1,2,3,4,5,6 10
How can I achieve that?
(For the curious: I tried my best to provide a reproducible example. Actual data involve a forecast of the number of items delivered from a wharehouse, which is stored in a list variable, and the number of days it takes to replenish them. The sum of the forecast from day one to day n (the lead time) is the number of items at which the supply process needs to be started again --reorder point--).
###### EDIT TO ADD #####
Consider the following case:
dt <- data.table(a = c(1, 3, 3, 4), b = c(list(1:6), list(2:7), list(3:8), list(4:9)))
The expected result will be:
dt[, c]
# 1 9 12 22
dt[, v := Map(extract, b, lapply(a, seq_len)) %>% sapply(sum)](just syntactic sugar on mt1022's answer)