Search code examples
rdata.tableseq

Error using seq in data.table r


I have a data.table like this:

DT <- data.table(year = rep(2009,24), id = rep(123,24), cant = c(rep(29,4),rep(30,12),rep(31,8)),
             monthr = c(seq(1,4,1),seq(1,12,1),seq(1,8,1)), count = c(rep(4,4),rep(12,12),rep(8,8)))

I want to compute a new var called pond using seq as follows:

DT[ , pond := ifelse(test = count < 12 && year == 2009,
                             yes = seq(12 - count + 1, 12, 1),
                             no = seq_along(cant)),by = c("id","cant")]

But I get the following error:

#Error in seq.default(12 - count + 1, 12, 1) : 'from' must be of length 1

I suppose that the error comes from the use name of vars in seq, but I don't known how to solve it. What can I do?


Solution

  • Based on the OP's example, 'count' is unique for each 'id', 'cant' group, so after grouping by 'id' and 'cant', specify the logical condition for 'year' in i, if the first value of 'count' is less than 12, get the sequence as showed in the OP's post or else return the sequence of rows, assign (:=) the output to 'pond'

    DT[year == 2009, pond := if(count[1] < 12) as.integer(seq(12-count[1] +1, 12, 1))
                        else seq_len(.N), .(id, cant)]