5
DT <- data.table(A = 1:5, B = 2:6, C = 3:7)

I want to make summation of 3 columns using column index:

DT[, D := do.call(sum, .SD), .SDcols = 1:3]

but code above doesnt work,

also I dont want to use DT[, D := (A+B+C)]

Psidom
  • 209,562
  • 33
  • 339
  • 356
evgenii ershenko
  • 489
  • 1
  • 5
  • 14

1 Answers1

15

You can use rowSums on .SD:

DT[, D := rowSums(.SD), .SDcols = 1:3][]

#   A B C  D
#1: 1 2 3  6
#2: 2 3 4  9
#3: 3 4 5 12
#4: 4 5 6 15
#5: 5 6 7 18
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Can you please give more information about ```.SD``` and ```.SDcols``` ?? Thanks! – RxT Jan 28 '20 at 19:22