Andres Mora
Andres Mora

Reputation: 1106

How to group by day and then count by a specific category?

My test dataset

Date        Fruit
01/01/2021  Apple
01/01/2021  Apple
01/01/2021  Lemon
02/01/2021  Lemon
03/01/2021  Peach
03/01/2021  Apple

I require to group by date and then count by each type of fruit, so The resulting dataframe should look something like this

Date         Apple   Lemon  Peach
01/01/2021   2       1      0
02/01/2021   0       1      0
03/01/2021   1       0      1

Upvotes: 1

Views: 50

Answers (2)

Andres Mora
Andres Mora

Reputation: 1106

df1 = df %>%  count (as.Date(Date), Fruit) %>%
              pivot_wider(names_from = Fruit, values_from = n)

Upvotes: 0

Hamid G
Hamid G

Reputation: 84

Let's say your data frame is, d:

table(d$Date, d$Fruit)
            
 #            Apple Lemon Peach
 # 01/01/2021     2     1     0
 # 02/01/2021     0     1     0
 # 03/01/2021     1     0     1

And if you want to save this as data frame object:

dd = data.frame(unclass(table(d$Date, d$Fruit)))

Upvotes: 1

Related Questions