4
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
  • 195,464
  • 25
  • 298
  • 322
evgenii ershenko
  • 427
  • 1
  • 5
  • 13

1 Answers1

13

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
  • 195,464
  • 25
  • 298
  • 322
  • Can you please give more information about ```.SD``` and ```.SDcols``` ?? Thanks! – RxT Jan 28 '20 at 19:22