Reputation: 13
I have a data.table with vectors or actually list with vector inside columns cells i.e.:
testDATA <- data.table('COLUMN_1' = list(1:4, 11:14, 21:24),
'COLUMN_ABC' = list(5:8, 25:28, 15:18),
'COLUMN1342' = list(2:5, 32:35, 22:25))
Additionally I have a vector with names of columns which vectors' elements I want to sum i.e.:
columnsToSum <- c('COLUMN_ABC', 'COLUMN1342')
How can I add column to data.table which will sum vectors' elements from columns defined in columnsToSum so that in the first row I will have vector c(6,8,10,12) ? I know that I can sum two vectors like this:
testDATA[, sumCol := list(Map(function(x,y) x + y, get('COLUMN_ABC'), get('COLUMN1342')))]
although the thing is that I have all columns which I should sum in columnsToSum vector. Any ideas?
Upvotes: 0
Views: 593
Reputation: 206308
I think this should work for you
testDATA[, sumCol := Reduce(function(a,b) Map(`+`,a,b), .SD),
.SDcols=columnsToSum]
We use .SD
to get a group of columns from the data table, then we use Reduce()
to sequentially add them up and use Map()
to add up each of the rows separately. It will work with more than 2 columns
columnsToSum <- names(testDATA)
testDATA[, sumCol := Reduce(function(a,b) Map(`+`,a,b), .SD), .SDcols=columnsToSum]
testDATA
# COLUMN_1 COLUMN_ABC COLUMN1342 sumCol
# 1: 1,2,3,4 5,6,7,8 2,3,4,5 23,31,39,47
# 2: 11,12,13,14 25,26,27,28 32,33,34,35 193,201,209,217
# 3: 21,22,23,24 15,16,17,18 22,23,24,25 153,161,169,177
Upvotes: 2