Search code examples
rdataframemean

Get daily average with R


I have a data.frame with some prices per day. I would like to get the average daily price in another column (avg_price). How can I do that ?

                   date   price   avg_price
1   2017-01-01 01:00:00   10      18.75
2   2017-01-01 01:00:00   10      18.75
3   2017-01-01 05:00:00   25      18.75
4   2017-01-01 04:00:00   30      18.75
5   2017-01-02 08:00:00   10      20
6   2017-01-02 08:00:00   30      20
7   2017-01-02 07:00:00   20      20

Solution

  • library(lubridate)
    library(tidyverse)
    
    df %>%  
      group_by(day = day(date)) %>% 
      summarise(avg_price = mean(price))
    
    # A tibble: 2 x 2
        day avg_price
      <int>     <dbl>
    1     1      18.8
    2     2      20  
    
    df %>%  
      group_by(day = day(date)) %>%  
      mutate(avg_price = mean(price))
    
    # A tibble: 7 x 4
    # Groups:   day [2]
      date                price avg_price   day
      <dttm>              <dbl>     <dbl> <int>
    1 2017-01-01 01:00:00    10      18.8     1
    2 2017-01-01 01:00:00    10      18.8     1
    3 2017-01-01 05:00:00    25      18.8     1
    4 2017-01-01 04:00:00    30      18.8     1
    5 2017-01-02 08:00:00    10      20       2
    6 2017-01-02 08:00:00    30      20       2
    7 2017-01-02 07:00:00    20      20       2