Skip to content

error in rowSums in data.table

2 messages · Camilo Mora, Rainer Schuermann

#
hi:

I have a datatable with two columns (see below) and I want to create  
another column that adds the values of the rows in the first two  
columns. I am trying this:

DT[ , col3 :=rowSums(.SD, na.rm = TRUE), .SDcols = c("col1","col2")]

but I get this error:
Error in inherits(x, "data.frame") : object '.SD' not found

do you know why is this? or is there another way to sum by row in a  
given number of columns?

Cheers,

Camilo




#        col1      col2      col3
#1:        NA  0.003745  0.003745
#2:  0.000000  0.007463  0.007463
#3: -0.015038 -0.007407 -0.022445
#4:  0.003817 -0.003731  0.000086
#5: -0.011407 -0.007491 -0.018898
#
On Thursday 30 May 2013 02:57:04 Camilo Mora wrote:

            
Without data.table:

x <- structure(list(col1 = c(NA, 0, -0.015038, 0.003817, -0.011407
), col2 = c(0.003745, 0.007463, -0.007407, -0.003731, -0.007491
)), .Names = c("col1", "col2"), class = "data.frame", row.names = c(NA,
-5L))

x[ is.na( x ) ] <- 0
x$col3 <- x$col1 + x$col2
col1      col2      col3
1  0.000000  0.003745  0.003745
2  0.000000  0.007463  0.007463
3 -0.015038 -0.007407 -0.022445
4  0.003817 -0.003731  0.000086
5 -0.011407 -0.007491 -0.018898