1

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
1
  • 1
    If you're willing to load magrittr, there's dt[, v := Map(extract, b, lapply(a, seq_len)) %>% sapply(sum)] (just syntactic sugar on mt1022's answer) Commented Apr 11, 2018 at 3:26

1 Answer 1

2

Since the operation is rowwise, we can use mapply instead of grouping by row:

dtt[, newCol := mapply(function(x, y) sum(y[1:x]), a, b)]

and personally I would avoid using c or dt for a variable or column name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.