上一年的值

Values from previous year

有什么方法可以从同一个 table 中获取包含前几年的值的新列?

数据: 图书馆(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 = 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) )

转换为Dateclass,然后按'Hospital'和年份标准化'Date'列进行分组,得到[=21的lead值=] 并将 (:=) 指定为新列

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'))]

-输出

> 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