Alberto Camacho
Alberto Camacho

Reputation: 13

R help calculate a mean for several months over several years

I need help finding the monthly average of gold from 1950 to 2018 this is what my data looks like

str(gold)
'data.frame':   827 obs. of  2 variables:
 $ Date : Factor w/ 827 levels "1950-01","1950-02",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Price: num  34.7 34.7 34.7 34.7 34.7 ...

> head(gold)
Date Price
1 1950-01 34.73
2 1950-02 34.73
3 1950-03 34.73
4 1950-04 34.73
5 1950-05 34.73
6 1950-06 34.73

> tail(gold)
Date   Price
822 2018-06 1282.13
823 2018-07 1238.06
824 2018-08 1201.86
825 2018-09 1199.20
826 2018-10 1214.73
827 2018-11 1221.28

I found the mean of each month for each year but now I am not sure how take the mean for each month over that span of time.

Upvotes: 0

Views: 367

Answers (1)

NelsonGon
NelsonGon

Reputation: 13309

Is this what you're looking for?

df %>% 
    separate(Date, c("Year","Month")) %>% 
    group_by(Month) %>% 
    summarise(Mean = mean(Price))

   Month   Mean
   <chr>  <dbl>
 1 01      34.7
 2 02      34.7
 3 03      34.7
 4 04      34.7
 5 05      34.7
 6 06     658. 
 7 07    1238. 
 8 08    1202. 
 9 09    1199. 
10 10    1215. 
11 11    1221. 

Upvotes: 3

Related Questions