Gianluca78
Gianluca78

Reputation: 784

How to aggregate data with the dyplr package in R

I would like to understand how to write the following code using the dplyr package:

averageStepsDayType <- aggregate(
    NAreplacement$steps, 
    by=list(interval=NAreplacement$interval, dayType=NAreplacement$dayType), 
    mean
)

This is the original data frame:

> head(NAreplacement)
      steps       date interval dayType
1 1.7169811 2012-10-01        0 weekday
2 0.3396226 2012-10-01        5 weekday
3 0.1320755 2012-10-01       10 weekday
4 0.1509434 2012-10-01       15 weekday
5 0.0754717 2012-10-01       20 weekday
6 2.0943396 2012-10-01       25 weekday

And this is the desired output obtained with the above code:

> head(averageStepsDayType)
  interval dayType          x
1        0 weekday 2.25115304
2        5 weekday 0.44528302
3       10 weekday 0.17316562
4       15 weekday 0.19790356
5       20 weekday 0.09895178
6       25 weekday 1.59035639

Here is my try:

byDate <- group_by(NAreplacement, date)
averageStepsDayType <- summarize(byDate, mean(steps))

> head(averageStepsDayType)
        date    x
1 2012-10-01    37.38260
2 2012-10-02     0.43750
3 2012-10-03    39.41667
4 2012-10-04    42.06944
5 2012-10-05    46.15972
6 2012-10-06    53.54167

Could someone give me an example? I suppose it should be a combination between the select and group_by functions but I have not figured out how.

Upvotes: 0

Views: 233

Answers (1)

akrun
akrun

Reputation: 887148

Try

library(dplyr)
NAreplacement %>% 
      group_by(interval, dayType) %>%
      summarise(x=mean(steps))

Upvotes: 2

Related Questions