我是R的新手。我有一個假設的資料集,其中包含來自不同病人和藥物型別的處方。我想做的是創建藥物使用的情節,也就是說,我想看看一個病人使用藥物的時間。依次更新 data.table 中的行中提到的回圈對我有用,但我不確定如何確保在遇到新的患者識別符號或藥物型別時,回圈能夠重新開始。
這些是來自資料集 "AllDrugs "的一些行:
DrugType ID Duration StartPrescr EndPrescr n
1 1 90 5-3- 2020 3-6-2020 1
1 2 30 7-1- 2020 6-2-2020 1
1 2 30 14-1- 2020 12-6-2020 2
1 2 30 21-01- 2020 19-6-2020 3
注意:n是一個數字,表示按ID和DrugType的處方
。這是當前的回圈:
for (i in 2: nrow(AllDrugs)) {
if (AllDrugs[/span>i。 StartPrescr] > = AllDrugs[i-1。 EndPrescr]) {
AllDrugs[i, EndPrescr:= StartPrescr Duration]
} else {{/span
AllDrugs[i, EndPrescr: = AllDrugs[i-1。 EndPrescr] Duration]
}
}
這就是我得到的:
這就是我得到的。
DrugType ID Duration StartPrescr EndPrescr n
1 1 90 5-3- 2020 3-6-2020 1
1 2 30 7-1- 2020 3-7-2020 1
1 2 30 14-1- 2020 2-8-2020 2
1 2 30 21-01- 2020 1-9-2020 3
這就是我想要的:
DrugType ID Duration StartPrescr EndPrescr n
1 1 90 5-3- 2020 3-6-2020 1
1 2 30 7-1- 2020 6-2-2020 1
1 2 30 14-1- 2020 7-3-2020 2
1 2 30 21-01- 2020 6-4-2020 3
我如何根據ID和DrugType的處方持續時間來轉移處方?注意:這是一個藥物型別的例子,但DrugType也可以是2,或3等等。
uj5u.com熱心網友回復:
這對你有用嗎?
shift_end < - function(en,dur) {>
if(length(en)> 1) for(i in 2。 length(en))en[i] =en[i-1] dur[i]
return(en)
}
df[order(ID, DrugType。 StartPrescr),EndPrescr。 =shift_end(EndPrescr,Duration),by=. (ID,DrugType)】。
結果:
DrugType ID Duration StartPrescr EndPrescr n
1。 1 1 90 2020-03- 05 2020-06-03 1
2: 1 2 30 2020-01- 07 2020-02-06 1
3: 1 2 30 2020-01- 14 2020-03-07 2
4: 1 2 30 2020-01- 21 2020-04-06 3
資料來源:
df <-結構(list()
DrugType = c(1。 1。 1, 1),
ID = c(1。 2。 2, 2),
持續時間 = c(90。 30。 30, 30),
StartPrescr =結構(c(18326。 18268。 18275, 18282)。 class = "Date"),
EndPrescr =結構(c(18416。 18298, 18425。 18432)。 class = "Date"),
n = c(1。 1。 2。 3)),行。 names = c(NA。 -4L),
class = c("data. table", "data.frame")
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/309968.html
標籤:
