1

I'd like to create a new data.table column by adding columns whose names match a certain expression. I don't know how many columns I'll be adding. The catch is, the columns are of class 'integer64' so rowSums(.) does not appear to work on them.

For instance, this works for two (known) integer64 columns:

DT <- data.table(a=as.integer64(1:4),b=as.integer64(5:8),c=as.integer64(9:12))
DT[, y := .SD[, 1] + .SD[, 2], .SDcols=c("a", "b")]

And this works for my case, any number of columns, but not if their class is integer64:

DT[, y := rowSums(.SD), .SDcols=c("a", "b")]  # gives incomprehensible data if class of a and b is integer64

One way I can work around it is by defining the data type of the column y beforehand. Is there a simpler way to do it? I may be missing something simple here and I apologize if that's so.

Naumz
  • 481
  • 5
  • 15
  • 1
    ```DT[, y := Reduce(`+`, .SD), .SDcols=c("a", "b")]``` seem to work. It seems like the problem is cause by to `matrix` conversion that `rowSums` does. – David Arenburg Jan 29 '17 at 07:09
  • @DavidArenburg `Reduce` is such a useful function, thank you! Would you like to post it as an answer? – Naumz Jan 29 '17 at 07:18
  • 2
    I don't think it's a general solution though. It works nicely for sum but can't handle NAs. I think either melting/dcasting the data or some general solution for to matrix transformation should be more general. See also [here](http://stackoverflow.com/questions/28262301/how-to-convert-a-data-frame-of-integer64-values-to-be-a-matrix) – David Arenburg Jan 29 '17 at 08:38

0 Answers0