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

Groupby, filter, summarise and then apply the result to the whole column

I am working with R and I have a series x at quarterly frequency and for which I want to extract the mean over the four quarters in 2012 and store that value in all rows of a newly created column. I have this kind of dataset

date durabl services 
2011-10-01 56.7 37.1
2012-01-01 68.1 90.6
2012-04-01 34.1 29.1
2012-07-01 22.56 34.12
2012-10-01 44.89 66.8

And I want to get to this

date durabl services base_durabl base_services
2011-10-01 56.7 37.1 42.4125 55.155
2012-01-01 68.1 90.6 42.4125 55.155
2012-04-01 34.1 29.1 42.4125 55.155
2012-07-01 22.56 34.12 42.4125 55.155
2012-10-01 44.89 66.8 42.4125 55.155

I tried using dplyr

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

df %>% group_by(year(date)) %>% filter(year(date)==2012) %>% mutate(base_durabl= mean(durabl),base_services=mean(services))

or with summarise but of course I just get a smaller tibble.

>Solution :

You can simply index the rows of services and durabl for which you want the mean estimated:

df %>% 
  mutate(base_durabl = mean(durabl[year(date)==2012]),
         base_services = mean(services[year(date)==2012]))

Output:

         date durabl services base_durabl base_services
1: 2011-10-01  56.70    37.10     42.4125        55.155
2: 2012-01-01  68.10    90.60     42.4125        55.155
3: 2012-04-01  34.10    29.10     42.4125        55.155
4: 2012-07-01  22.56    34.12     42.4125        55.155
5: 2012-10-01  44.89    66.80     42.4125        55.155
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