Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values in two data.tables

Tags:

r

data.table

I have two data.tables, and one has a subset of rows/columns of another. I'd like to add values of the smaller data.table to the values of the larger one:

DT1 <- as.data.table(matrix(c(0, 1, 2, 3), nrow=2, ncol=2, 
       dimnames=list(c("a", "b"), c("a", "b"))), keep=T)
DT2 <- as.data.table(matrix(c(0, 0, 1, 2, 2, 1, 1, 0, 3), nrow=3, ncol=3, 
       dimnames=list(c("a", "b", "c"), c("a", "b", "c"))), keep=T)

DT1
#   rn a b
#1:  a 0 2
#2:  b 1 3
DT2
#   rn a b c
#1:  a 0 2 1
#2:  b 0 2 0
#3:  c 1 1 3

I'd like to add DT1 to DT2 so that I get

#   rn a b c
#1:  a 0 4 1
#2:  b 1 5 0
#3:  c 1 1 3

I know I can overwrite values of DT2 with DT1 very easily:

DT2[DT1, names(DT1) := DT1, on="rn"]

I was hoping that something like this would work:

DT2[DT1, names(DT1) := DT1 + .SD, on="rn"]

...but it doesn't. There's probably some simple variation on this that would work, though, right?

like image 726
Stan Avatar asked Sep 27 '15 01:09

Stan


People also ask

How do I connect two data tables in Spotfire?

When you configure an analysis in TIBCO Spotfire, you may want to be able to visualize data from more than one data table. Adding other data tables is fairly easy; just click Files and data on the authoring bar, and select the data source of interest.


1 Answers

You can use rbindlist() to bring the two together, then sum the values based on rn

rbindlist(list(DT1, DT2), fill=TRUE)[, lapply(.SD, sum, na.rm = TRUE), by = rn]
#    rn a b c
# 1:  a 0 4 1
# 2:  b 1 5 0
# 3:  c 1 1 3
like image 56
Rich Scriven Avatar answered Oct 07 '22 10:10

Rich Scriven