循环以创建总药物持续时间的变量

时间:2017-11-02 19:07:23

标签: r

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 ** 有谁知道我在这里做错了什么? 感谢!!!

1 个答案:

答案 0 :(得分:0)

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

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

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

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

你也可以用一个不算0的函数替换长度参数。