I am using the mtcars
dataset. I want to find the number of records for a particular combination of data. Something very similar to the count(*)
group by clause in SQL. ddply()
from plyr is working for me
library(plyr)
ddply(mtcars, .(cyl,gear),nrow)
has output
cyl gear V1
1 4 3 1
2 4 4 8
3 4 5 2
4 6 3 2
5 6 4 4
6 6 5 1
7 8 3 12
8 8 5 2
Using this code
library(dplyr)
g <- group_by(mtcars, cyl, gear)
summarise(g, length(gear))
has output
length(cyl)
1 32
I found various functions to pass in to summarise()
but none seem to work for me. One function I found is sum(G)
, which returned
Error in eval(expr, envir, enclos) : object 'G' not found
Tried using n()
, which returned
Error in n() : This function should not be called directly
What am I doing wrong? How can I get group_by()
/ summarise()
to work for me?
ddply
. What version of dplyr are you on? Try updating? – Wanglesum(G)
example doesn't work because presumablyG
doesn't exist. Maybe you meantg
? And your example also works fine for me usingn()
. – Wangleg
was actually not grouped. So I would look for a reason why you might be somehow ungrouping your data frame. – Wanglemtcars %.% group_by(cyl, gear) %.% summarise(length(gear))
, it gives the same result. – Desdamonna