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

Time:12-05

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

CodePudding user response:

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)))

CodePudding user response:

df1 = df %>%  count (as.Date(Date), Fruit) %>%
              pivot_wider(names_from = Fruit, values_from = n)
  •  Tags:  
  • r
  • Related