0
我有处方记录数据,并想知道每个人每年从发行日期到其记录结束时有多少处方。实施例的数据(第5行的每个ID的):如何创建连续列(R)
ID Issue_Date index.date other.drugs
1: 1 2000-02-08 2011-02-03 1
2: 1 2000-04-04 2011-02-03 0
3: 1 2000-05-30 2011-02-03 1
4: 1 2000-07-25 2011-02-03 1
5: 1 2000-08-22 2011-02-03 1
---
1: 2 2007-03-23 2009-04-03 1
2: 2 2007-04-04 2009-04-03 1
3: 2 2007-04-23 2009-04-03 1
4: 2 2007-04-23 2009-04-03 0
5: 2 2007-05-21 2009-04-03 1
的other.drugs
列是一个指示变量表示在该日期给出的处方是否不在研究兴趣的处方。 index.date
是他们进入研究的日期。有超过1000个ID
的,只有2个在这里给出。
我想每年在issue.date
之后找到每年other.drugs
的总和。我分别使用下面的代码计算出这第一年:
dt <- dt[, yearend.1 := Issue_Date[1]+365, by = ID]
dt <- dt[(Issue_Date<=yearend.1), comorbid.1 := sum(other.drugs), by = ID]
dt <- dt[, comorbid.1:= comorbid.1[!is.na(comorbid.1)][1], by = ID]
# the last line copies the value to each cell the ID occupies in the data.table for that column instead of having NA's
这给了以下结果:
ID Issue_Date index.date other.drugs yearend.1 comorbid.1
1: 1 2000-02-08 2011-02-03 1 2001-02-07 8
2: 1 2000-04-04 2011-02-03 1 2001-02-07 8
3: 1 2000-05-30 2011-02-03 1 2001-02-07 8
4: 1 2000-07-25 2011-02-03 1 2001-02-07 8
5: 1 2000-08-22 2011-02-03 1 2001-02-07 8
---
1: 2 2007-03-23 2009-04-03 1 2008-03-22 30
2: 2 2007-04-04 2009-04-03 1 2008-03-22 30
3: 2 2007-04-23 2009-04-03 1 2008-03-22 30
4: 2 2007-04-23 2009-04-03 1 2008-03-22 30
5: 2 2007-05-21 2009-04-03 1 2008-03-22 30
解读:ID 1后,他们的第一个issue_date
规定在今年8种其他药物和ID 2遵医嘱30.
多年来2-10(有一个最大为11年的记录)我写下面的循环:
years <- seq(730, 3650, 365)
# number of days in 2-10 years.
years2 <- seq(2,10,1)
# numbering the years for column names
colnames <- paste0("yearend.", years2)
colnames2 <- paste0("comorbid.", years2)
# names of columns to be used
for (i in 1:length(years)) {
dt <- dt[, colnames[i] := Issue_Date[1]+years[i], by = ID]
dt <- dt[(Issue_Date>=(as.Date(colnames[i], "%d-%m-%Y")) & Issue_Date<(as.Date(colnames[i+1], "%d-%m-%Y"))),
colnames2[i] := sum(other.drugs), by = ID]
dt <- dt[, colnames2[i]:= colnames2[i][!is.na(colnames2[i])][1], by = ID]
}
但是应该已经创造了新的栏目有:
ID Issue_Date index.date other.drugs yearend.1 comorbid.1 yearend.2 comorbid.2 yearend.3 comorbid.3
1: 1 2000-02-08 2011-02-03 1 2001-02-07 8 2002-02-07 comorbid.2 2003-02-07 comorbid.3
2: 1 2000-04-04 2011-02-03 1 2001-02-07 8 2002-02-07 comorbid.2 2003-02-07 comorbid.3
3: 1 2000-05-30 2011-02-03 1 2001-02-07 8 2002-02-07 comorbid.2 2003-02-07 comorbid.3
4: 1 2000-07-25 2011-02-03 1 2001-02-07 8 2002-02-07 comorbid.2 2003-02-07 comorbid.3
5: 1 2000-08-22 2011-02-03 1 2001-02-07 8 2002-02-07 comorbid.2 2003-02-07 comorbid.3
---
我想知道什么是我的循环去错了。非常感谢帮助。