Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading