【问题标题】:Loop to create a Variable for Total Drug Duration循环创建总药物持续时间的变量
【发布时间】:2017-11-02 19:07:22
【问题描述】:

dput(head(data,20))的输出

structure(list(Id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), time = 1:20, Event = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), Fup = c(90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 
90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L), 
    Start = 1:20, Stop = 2:21, dose = c(0, 0, 2.6, 2.6, 2.6, 
    2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 
    2.6, 2.6, 2.6)), .Names = c("Id", "time", "Event", "Fup", 
"Start", "Stop", "dose"), row.names = c(NA, 20L), class = "data.frame")

我需要在我的数据集中创建一个变量,名为:药物使用的总持续时间(在给定患者的整个随访期间),我正在创建以下循环:

list.id <- unique(data$Id)

nbr.subjects <- length(list.id)

tot.dur.use <- NULL

for (i in 1:nbr.subjects) {
    current.subject <- data[data$Id == list.id[i], ]
    tot.dur.use.tmp <- sum(current.subject$dose != 0)
    tot.dur.use <- c(tot.dur.use, tot.dur.use.tmp)
}
data <- cbind(data, tot.dur.use)

给出以下错误:**data.frame(..., check.names = FALSE) 中的错误: 参数意味着不同的行数:70255、498 ** 有谁知道我在这里做错了什么? 谢谢!!!

【问题讨论】:

  • 请提供数据集data,或者如果它非常大,请提供它的样本。使用dput(data) 并在您的问题中发布结果。
  • tot.dur.use &lt;- c(tot.dur.use, tot.dur.use.tmp),而不是tot.dur.use.tmp &lt;- c(...)
  • 数据集相当大,但这里是 head(data) 的结果: Id time Event Fup Start Stop dose 1 1 1 0 90 1 2 0.0 2 1 2 0 90 2 3 0.0 3 1 3 0 90 3 4 2.6 4 1 4 0 90 4 5 2.6 5 1 5 0 90 5 6 2.6 6 1 6 0 90 6 7 2.6
  • @RuiBarradas,我试着希望循环:tot.dur.use.tmp
  • 抱歉,suminstruction 是新的,它在您的代码中的什么位置?使用该更改和head(data) 的输出编辑问题,不要将其放在评论中。发布dput(head(data, 20)) 的输出比简单的head(...) 更好。

标签: r


【解决方案1】:

这是我的data.table 解决方案。这给出了一个运行总计。

library("data.table")
setDT(data)
data[,tot.dur := cumsum(dose),by=Id]
data

如果您想要避免 0 的运行计数,则将 cumsum 函数替换为 length2&lt;-function(x){x[x!=0]&lt;-1:sum(x!=0);x}。如果您想按 Id 聚合并获得总的非 0 剂量计数。

data2<-data[dose!=0] #Remove rows with 0 dose
data[, lapply(.SD, length), by=Id]

您也可以将长度参数替换为不计算 0 的函数。

【讨论】:

  • ,感谢您的帮助!有效!如果我只想查看最近 30 天的使用情况,我想请您就如何修改函数(cumsum(dose))提出建议。
  • 这就是我想要做的:data2[,tot.cum.use.30 := cumsum((tail(data2$id,30)$dose)), by = id]但它并没有真正起作用..
  • 您已经很接近了,但只需将其放入类似 cumsum30&lt;-function(x){cumsum(tail(x,n=30))} 的函数中即可。请选择此答案作为最佳答案,以便人们知道问题已得到解答。
猜你喜欢
  • 2022-12-14
  • 2019-03-22
  • 2020-10-21
  • 1970-01-01
  • 2021-10-02
  • 2012-06-01
  • 2021-08-11
  • 2018-12-13
  • 1970-01-01
相关资源
最近更新 更多