Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum columns values in data.table in r using .SDcols [duplicate]

Tags:

r

data.table

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)]

like image 379
evgenii ershenko Avatar asked Dec 15 '22 00:12

evgenii ershenko


1 Answers

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
like image 145
Psidom Avatar answered Mar 05 '23 07:03

Psidom