3
$\begingroup$

I have a data table of 5 columns. I want to do a group by on one column and want to get the count of another column, id.

I do this in this way: dt[,length(id),by=dt$cid].

If I also want to get sum of id, how do I proceed? I tried this:

dt[,(sum(id) length(id)),by=dt$cid]

but it did not work. Could you please help out.

Thanks

$\endgroup$
  • $\begingroup$ You could use the sqldf package. $\endgroup$ – Hidden Markov Model Aug 4 '15 at 1:08
  • $\begingroup$ Please read this. Your syntax is incorrect. $\endgroup$ – David Arenburg Sep 4 '15 at 7:11
3
$\begingroup$

If you want to get but the sum and length of id with data.table, you can do it like this:

dt[,.(total=sum(id), n=length(id)), by=cid]

You could even write this in shorter format with the .N operator of data.table:

dt[,.(total=sum(id), .N), by=cid]
|improve this answer|||||
$\endgroup$
  • $\begingroup$ +1 for using .N. This is probably the most efficient. $\endgroup$ – Sam May 19 '16 at 15:32
1
$\begingroup$

Use tapply,

with(dt,tapply(id, cid, FUN=sum))
|improve this answer|||||
$\endgroup$
  • $\begingroup$ This will only find the sum. And it is better to say "You could use" $\endgroup$ – David Arenburg Sep 4 '15 at 7:10
1
$\begingroup$

You can use tapply or aggregate along with a custom function.

aggregate(Id~cid, data=dt, FUN=function(x) c(mn=mean(x),ln=length(x)))

You may like to see my blog where I discuss few other scenario.

http://r4sqlminded.blogspot.com/2015/06/selecting-data-from-data-frame.html

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.