【发布时间】:2018-07-31 02:36:05
【问题描述】:
是否有任何替代方法来替换 dplyr 下的以下代码以避免显式循环和数据名称来实现以下?
这是创建一个调整的日期,如果当前 supp_date 小于前一个 supp_date + tablet 的条件满足。
示例数据:(这是包含else case 的新示例数据。)
test <- read.table(text =
"supp_date tablet
2017-07-19 30
2017-08-07 30
2017-09-08 30
2017-10-30 30
2017-11-08 30
2017-12-07 30", header = T)
R 代码:
test$supp_date <- as.Date(test$supp_date, "%Y-%m-%d")
test$adj_fill_dt <- as.Date(NA, "%Y-%m-%d")
test$adj_fill_dt[1] <- test$supp_date[1]
for(i in 2:6) {
if (test[i, "supp_date"] < test[i-1, "adj_fill_dt"] + test[i-1, "tablet"]) {
test[i, "adj_fill_dt"] <- test[i-1, "adj_fill_dt"] + test[i-1, "tablet"]
} else {
test[i, "adj_fill_dt"] <- test[i, "supp_date"]
}
}
发件人:
supp_date tablet
2017-07-19 30
2017-08-07 30
2017-09-08 30
2017-10-30 30
2017-11-08 30
2017-12-07 30
收件人:
supp_date tablet adj_fill_dt
2017-07-19 30 2017-07-19
2017-08-07 30 2017-08-18
2017-09-08 30 2017-09-17
2017-10-30 30 2017-10-30
2017-11-08 30 2017-11-29
2017-12-07 30 2017-12-29
【问题讨论】:
-
"target_dose"列中有什么内容?你的意思是tablet?我假设tablet的单位是天? -
@MauritsEvers 对此感到抱歉。对代码进行了一些编辑,忘记更改它。是的,你可以假设。