Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rowSums in a data table in R [duplicate]

Tags:

r

data.table

Was looking for a easy way to get the sum total of around 170 different columns in my data table as a new column. Is there some wild card notation I can use?

This following is a small extract (first few columns) from my dataset:

> head(t_checkin)
checkin_info_0.0 checkin_info_0.1 checkin_info_0.2 checkin_info_0.3 checkin_info_0.4 checkin_info_0.5
              NA               NA               NA               NA               NA                1
               3               NA               NA               NA               NA                1
              NA               NA                1               NA               NA               NA
              NA               NA               NA               NA               NA               NA
              NA               NA               NA               NA               NA               NA
              NA               NA               NA               NA               NA               NA

Any help would be greatly appreciated. Thanks

like image 813
Abi K Avatar asked Apr 09 '13 14:04

Abi K


1 Answers

EDIT

Correction, do what @MatthewDowle says:

dat <- data.frame(x=1:11,y=100:110,z=sample(letters,11))
DT <- as.data.table(dat)
names <- c("x","y")
DT[,lapply(.SD,sum),.SDcols=names]


mysum <- function(x){sum(x, na.rm=TRUE)}
DT[,lapply(.SD,mysum),.SDcols=names]
like image 132
user1317221_G Avatar answered Oct 22 '22 23:10

user1317221_G