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

Values from previous year

is there any way to get a new column containing values from the previous years from the same table?

DATA:
library(data.table)

table = data.table( Date =c( "01/01/2022", "01/10/2021", "01/07/2021", "01/04/2021", "01/01/2021", "01/10/2020", "01/07/2020"),
                    Hospital = "Hospital 1",
                    Patients = c(13,11,9,7,5,3,1) 
                    )

RESULT:

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

result = data.table( Date =c( "01/01/2022", "01/10/2021", "01/07/2021", "01/04/2021", "01/01/2021", "01/10/2020", "01/07/2020"),
                     Hospital = 'Hospital 1',
                    Patients = c(13,11,9,7,5,3,1),
                    Patients_previous_year = c(5,3,1,NA,NA,NA,NA) )

>Solution :

Convert to Date class, then do a grouping by ‘Hospital’ and year standardized ‘Date’ column, get the lead values of ‘Patients’ and assign (:=) as new column

library(data.table)
table[, Date := as.IDate(Date, '%m/%d/%Y')]
table[,  Patients_previous_year := shift(Patients, type = 'lead'),
    .(Hospital, grp = format(Date, '2022-%m-%d'))]

-output

> table
         Date   Hospital Patients Patients_previous_year
1: 2022-01-01 Hospital 1       13                      5
2: 2021-01-10 Hospital 1       11                      3
3: 2021-01-07 Hospital 1        9                      1
4: 2021-01-04 Hospital 1        7                     NA
5: 2021-01-01 Hospital 1        5                     NA
6: 2020-01-10 Hospital 1        3                     NA
7: 2020-01-07 Hospital 1        1                     NA
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