goldisfine
goldisfine

Reputation: 4850

Get count by column values

I have a dataframe that looks like this:

  month create_time request_id weekday
1     4  2014-04-25    3647895  Friday
2    12  2013-12-06    2229374  Friday
3     4  2014-04-18    3568796  Friday
4     4  2014-04-18    3564933  Friday
5     3  2014-03-07    3081503  Friday
6     4  2014-04-18    3568889  Friday

And I'd like to get the count of request_ids by the weekday. How would I do this in R?

I've tried a lot of stuff based on ddply and aggregate with no luck.

Upvotes: 0

Views: 88

Answers (4)

Rich Scriven
Rich Scriven

Reputation: 99371

Another option is to use a table and take the rowSums

> rowSums(with(dat, table(weekday, request_id)))
Friday 
     6 

Upvotes: 1

linp
linp

Reputation: 1517

or ... u could try:

count(df,"weekday")

or

library(plyr)
ddply(df,.(weekday),summarise,count=length(month))

Upvotes: 1

farnsy
farnsy

Reputation: 2470

There are several valid ways to do it. I usually go with my trusty sqldf(). If the dataframe is named D, then

library(sqldf)
counts <- sqldf('select weekday, count(request_id) as nrequests from D group by weekday')

sqldf() can be wordy, but it is just so easy to remember and get right the first time!

Upvotes: 2

Jilber Urbina
Jilber Urbina

Reputation: 61214

Try using aggregate

> aggregate(request_id ~ weekday, FUN=length, dat=df)
  weekday request_id
1  Friday          6

Upvotes: 2

Related Questions