Creat a reproducible data
set.seed(20220105)
begin = as.Date('1994-01-01')
end = as.Date('1994-12-31')
date_seq = seq(from = begin, to = end, by = '1 day')
length = length(date_seq)
death = sample(x = 1:100, size = length, replace = T)
temperature = sample(x = -25:25, size = length, replace = T)
df = data.frame(date = date_seq, death = death, temperature = temperature)
> head(df)
date death temperature
1 1994-01-01 66 20
2 1994-01-02 56 7
3 1994-01-03 33 -9
4 1994-01-04 29 -17
5 1994-01-05 6 0
6 1994-01-06 33 -15
Variable definition
Each day in df can be a case day and also can be a control day.
The case day and control days are matched by day of the week in the same month and in the same year.
Thus, each case has 3 or 4 control days (before and/or after the case day in the same month).
For example, when the case day is 1994-01-01, control days are 1994-01-08, 1994-01-15, 1994-01-22 and 1994-01-29.
When the case day is 1994-01-08, control days are 1994-01-01, 1994-01-15, 1994-01-22 and 1994-01-29.
What I needed
I want to creat a new df_wanted that based on the original df.
df_wanted should contain 5 varibales which 3 variables from the original df including date, death and temperature.
The death and temperature should be the case day's death and temperature.
The other 2 varibales are new variables.
One is status which indicates a day is case day or control day.
One is stratum. This variable like a group. Each group has one case day and three or four control day.
Some of the data in df_wanted should like this:
df_wanted = data.frame(
date = c('1994-01-01', '1994-01-08', '1994-01-15', '1994-01-22', '1994-01-29',
'1994-01-08', '1994-01-01', '1994-01-15', '1994-01-22', '1994-01-29'),
status = c(1,0,0,0,0, 1,0,0,0,0),
stratum = c(1,1,1,1,1, 2,2,2,2,2),
death = c(66, 66, 66, 66, 66, 1,1,1,1,1),
temperature = c(20,20,20,20,20, 13,13,13,13,13)
)
> df_wanted
date status stratum death temperature
1 1994-01-01 1 1 66 20
2 1994-01-08 0 1 66 20
3 1994-01-15 0 1 66 20
4 1994-01-22 0 1 66 20
5 1994-01-29 0 1 66 20
6 1994-01-08 1 2 1 13
7 1994-01-01 0 2 1 13
8 1994-01-15 0 2 1 13
9 1994-01-22 0 2 1 13
10 1994-01-29 0 2 1 13
What I have tried
I searched some answers, such as Create control dates in bilateral case crossover design and Create a case control pair for time stratified case-crossover design, but all the answers do not meet my need.
Any help will be highly appreciated!