I've got a dataset that looks like this
#Determine the M, M-1 and M-2 values for every site
df = data.frame(Site=c(rep('x',5),rep('y',5),rep('z',5)),
Date=c(as.Date('2020/09/11'),as.Date('2020/09/11'),
as.Date('2020/08/02'),as.Date('2020/07/09'),
as.Date('2020/05/15'),as.Date('2020/08/02'),
as.Date('2020/07/10'),as.Date('2020/07/19'),
as.Date('2020/06/27'),as.Date('2020/03/01'),
as.Date('2020/04/07'),as.Date('2020/01/01'),
as.Date('2019/11/10'),as.Date('2019/11/11'),
as.Date('2019/11/07')))
I'm trying to transform the dataset such that
I pick the top 3 most recent months from the Date column for each Site
Spread the Date column such that it is in 'M' 'M-1' and 'M-2' format
'M' being most recent month, 'M-1' being second most recent month, 'M-2' being third most recent month
Convert Date from YYYY/MM/DD format to Month-Year format e.g. 2020/01/01 = JAN 2020
My attempt
For step 1.
transformed = df %>%
group_by(Site) %>%
arrange(desc(Date)) %>%
slice(1:3)
This works fine up till here. I've been trying various ways of spreading the dates to the desired format, but I haven't succeeded. I'm a bit new to this so any inputs would help a lot.
Desired output
I'd like my desired output to look like this
#Output table
output = data.frame(Site=c('x','y','z'),
M=c('SEP 2020','AUG 2020','APR 2020'),
`M-1`=c('AUG 2020','JUL 2020','JAN 2020'),
`M-2`=c('JUL 2020','JUN 2020','NOV 2019'))
colnames(output)=c('Site','M','M-1','M-2')
Modification: September 21, 2020
I've slightly modified the original dataframe df
to factor in cases where we have more than one date in a given month. In such a situation, how can the solutions you've proposed be modified to get the same output
?