hk2
hk2

Reputation: 487

Perform group by on a column to calculate count of occurrences of another column in R

I have a dataset similar to sample dataset provided below:

| Name | Response_days | state |
|------|---------------|-------|
| John | 0             | NY    |
| John | 6             | NY    |
| John | 9             | NY    |
| Mike | 3             | CA    |
| Mike | 7             | CA    |

The same is represented as:

Name = c("John","John", "John", "Mike", "Mike")
Response_days = c(0,6,9,3,7)
state= c("NY","NY","NY", "CA","CA")
df= data.frame(Name, Response_days, state, stringsAsFactors = TRUE)
df$Response_days= as.integer(df$Response_days)

I want to subset the data and look at only the Response_days>5. After that I want to group by on 'Name' and count the occurrences of 'Response_days'. I have tried the code mentioned below but it throws an error.

df1=subset(df, df$Response_days>5) %>%  group_by(Name) %>%
  summarise(count= count(Response_days))

The error that I get is Error:

Problem with `summarise()` input `count`.
x no applicable method for 'count' applied to an object of class "c('double', 'numeric')"
i Input `count` is `count(Response_days)`.
i The error occurred in group 1: Name = "John".

Could someone please explain me where am I going wrong? Also, my final output should look something like the one below:

| Name | Response_days |
|------|---------------|
| John | 2             |
| Mike | 1             |

Upvotes: 3

Views: 1645

Answers (2)

akrun
akrun

Reputation: 886938

We can use data.table

library(data.table)
setDT(df)[Response_days > 5, .(count = .N), Name]

Or using base R

table(subset(df, Response_days > 5)$Name)
  

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388807

Here are couple ways to do this in dplyr -

library(dplyr)
#1.
df %>% filter(Response_days>5) %>% count(Name, name = 'Count')

#2.
df %>% group_by(Name) %>% summarise(count = sum(Response_days > 5))

and in base R :

#1.
aggregate(Response_days~Name, subset(df, Response_days>5), length)

#2.
aggregate(Response_days~Name, df, function(x) sum(x > 5))

Upvotes: 3

Related Questions