tobinz
tobinz

Reputation: 335

chaining in data.table to compute row sum

I have a transformed data.table like this:

name <- c("Bob","Mary","Jane","Kim")
weight <- c(60,65,45,55)
height <- c(170,165,140,135)
dft <- data.table(name,weight,height) 
dft <-  data.table (dft[,.(name)] ,     dft[, weight %*% t(weight)]) 
names(dft) <- c("name", str_c("tau",1:4))

Now I first multiply tau12 = tau1 * tau2 and compute the row sums across all the five columns, including tau12.

If I use

dft[,  `:=`(tau12 = tau1 * tau2, 
            sum1 = lapply(.SD, sum) ) , .SDcols = patterns("^tau")  ]
 

However, sum1 only computes the sum of four columns, not including the column tau12.

I wonder how to compute the sum tau1+tau2+tau3+tau4+tau12 in this case? This is different from what dplyr::mutate does, where the newly generated variables can be involved in subsequent operations.

Upvotes: 0

Views: 166

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101327

Something like this?

> dft[, tau12 := tau1 * tau2][, .(rowS = rowSums(.SD)), name, .SDcols = patterns("^tau")]       
   name     rowS
1:  Bob 14053500
2: Mary 16492125
3: Jane  7907625
4:  Kim 11809875

Upvotes: 1

Related Questions