[datatable-help] Row wise operation in data.table

Arunkumar Srinivasan aragorn168b at gmail.com
Fri Aug 30 09:13:55 CEST 2013


It'd be easier if you just `melt` your `data.table` by `id = Respid`. Then you get a long format with which you can use fast grouping to count the number of 3s. 

require(reshape2)
require(data.table)

setkey(as.data.table(melt(DT, id="Respid")), Respid)[value == 3, .N, by=Respid][DT]


Arun


On Friday, August 30, 2013 at 9:04 AM, Serdar Akin wrote:

> Hi, 
> 
> Currently I'm trying to find a way to make row wise operation within data.table to find value that have
> a certain pattern, and to count those. 
> 
> For instance find the number of 3 for each Respid and count those for each row.
> set.seed(1)
> DT    <- data.table( Respid = seq(1,100, 1), 
>                     Q1 = rep(1:5, each = 20), 
>                     Q2 = as.integer(runif(100, min = 1, max = 5) ),
>                     Q3   = sample(1:5, 100, replace = T)
> )
> 
> DT1    <- DT[, lapply(.SD, function(x) length(grep(3, x))), by = 'Respid']
> 
> A do get 1 for each column that has a 3 in it but no column that counts it. 
> 
> Regards Serdar 
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org (mailto:datatable-help at lists.r-forge.r-project.org)
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help
> 
> 


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20130830/0b680f09/attachment.html>


More information about the datatable-help mailing list