在 ggplot 或lattice 中利用 Surv 对象

发布于 2024-09-04 07:50:47 字数 772 浏览 9 评论 0原文

有人知道如何利用 ggplot 或lattice 进行生存分析吗?制作网格或类似面的生存图会很好。


所以最后我尝试了一下,找到了卡普兰-迈耶图的解决方案。对于将列表元素放入数据框中的混乱代码,我深表歉意,但我无法找出其他方法。

注意:它仅适用于两层地层。如果有人知道我如何使用 x<-length(stratum) 来执行此操作,请告诉我(在 Stata 中,我可以附加到宏 - 不确定这在 R 中如何工作)。

ggkm<-function(time,event,stratum) {

    m2s<-Surv(time,as.numeric(event))

    fit <- survfit(m2s ~ stratum)

    f$time <- fit$time

    f$surv <- fit$surv

    f$strata <- c(rep(names(fit$strata[1]),fit$strata[1]),
            rep(names(fit$strata[2]),fit$strata[2])) 

    f$upper <- fit$upper

    f$lower <- fit$lower

    r <- ggplot (f, aes(x=time, y=surv, fill=strata, group=strata))
        +geom_line()+geom_ribbon(aes(ymin=lower,ymax=upper),alpha=0.3)

    return(r)
}

Anyone knows how to take advantage of ggplot or lattice in doing survival analysis? It would be nice to do a trellis or facet-like survival graphs.


So in the end I played around and sort of found a solution for a Kaplan-Meier plot. I apologize for the messy code in taking the list elements into a dataframe, but I couldnt figure out another way.

Note: It only works with two levels of strata. If anyone know how I can use x<-length(stratum) to do this please let me know (in Stata I could append to a macro-unsure how this works in R).

ggkm<-function(time,event,stratum) {

    m2s<-Surv(time,as.numeric(event))

    fit <- survfit(m2s ~ stratum)

    f$time <- fit$time

    f$surv <- fit$surv

    f$strata <- c(rep(names(fit$strata[1]),fit$strata[1]),
            rep(names(fit$strata[2]),fit$strata[2])) 

    f$upper <- fit$upper

    f$lower <- fit$lower

    r <- ggplot (f, aes(x=time, y=surv, fill=strata, group=strata))
        +geom_line()+geom_ribbon(aes(ymin=lower,ymax=upper),alpha=0.3)

    return(r)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦太阳 2024-09-11 07:50:48

我一直在lattice中使用以下代码。第一个函数绘制一个组的 KM 曲线,通常用作 panel.group 函数,而第二个函数添加整个面板的对数秩检验 p 值:

 km.panel <- function(x,y,type,mark.time=T,...){
     na.part <- is.na(x)|is.na(y)
     x <- x[!na.part]
     y <- y[!na.part]
     if (length(x)==0) return()
     fit <- survfit(Surv(x,y)~1)
     if (mark.time){
       cens <- which(fit$time %in% x[y==0])
       panel.xyplot(fit$time[cens], fit$surv[cens], type="p",...)
      }
     panel.xyplot(c(0,fit$time), c(1,fit$surv),type="s",...)
}

logrank.panel <- function(x,y,subscripts,groups,...){
    lr <-  survdiff(Surv(x,y)~groups[subscripts])
    otmp <- lr$obs
    etmp <- lr$exp
    df <- (sum(1 * (etmp > 0))) - 1
    p <- 1 - pchisq(lr$chisq, df)
    p.text <- paste("p=", signif(p, 2))
    grid.text(p.text, 0.95, 0.05, just=c("right","bottom"))
    panel.superpose(x=x,y=y,subscripts=subscripts,groups=groups,...)
}

审查指标有为 0-1 才能使此代码正常工作。用法如下:

library(survival)
library(lattice)
library(grid)
data(colon)  #built-in example data set
xyplot(status~time, data=colon, groups=rx, panel.groups=km.panel, panel=logrank.panel)

如果您只使用“panel=panel.superpose”,那么您将无法获得 p 值。

I have been using the following code in lattice. The first function draws KM-curves for one group and would typically be used as the panel.group function, while the second adds the log-rank test p-value for the entire panel:

 km.panel <- function(x,y,type,mark.time=T,...){
     na.part <- is.na(x)|is.na(y)
     x <- x[!na.part]
     y <- y[!na.part]
     if (length(x)==0) return()
     fit <- survfit(Surv(x,y)~1)
     if (mark.time){
       cens <- which(fit$time %in% x[y==0])
       panel.xyplot(fit$time[cens], fit$surv[cens], type="p",...)
      }
     panel.xyplot(c(0,fit$time), c(1,fit$surv),type="s",...)
}

logrank.panel <- function(x,y,subscripts,groups,...){
    lr <-  survdiff(Surv(x,y)~groups[subscripts])
    otmp <- lr$obs
    etmp <- lr$exp
    df <- (sum(1 * (etmp > 0))) - 1
    p <- 1 - pchisq(lr$chisq, df)
    p.text <- paste("p=", signif(p, 2))
    grid.text(p.text, 0.95, 0.05, just=c("right","bottom"))
    panel.superpose(x=x,y=y,subscripts=subscripts,groups=groups,...)
}

The censoring indicator has to be 0-1 for this code to work. The usage would be along the following lines:

library(survival)
library(lattice)
library(grid)
data(colon)  #built-in example data set
xyplot(status~time, data=colon, groups=rx, panel.groups=km.panel, panel=logrank.panel)

If you just use 'panel=panel.superpose' then you won't get the p-value.

灯下孤影 2024-09-11 07:50:48

我开始几乎完全遵循您在更新的答案中使用的方法。但 survfit 令人恼火的是它只标记变化,而不是每个刻度 - 例如,它会给你 0 - 100%、3 - 88%,而不是 0 - 100%、1 - 100%、2 - 100 %, 3 - 88%。如果将其输入 ggplot,您的线条将从 0 倾斜到 3,而不是保持平坦并直接下降到 3。根据您的应用程序和假设,这可能没问题,但这不是经典的 KM 图。这就是我处理不同数量的地层的方式:

groupvec <- c()
for(i in seq_along(x$strata)){
    groupvec <- append(groupvec, rep(x = names(x$strata[i]), times = x$strata[i]))
}
f$strata <- groupvec

对于它的价值,这就是我最终这样做的方式 - 但这也不是真正的 KM 图,因为我本身并没有计算出 KM 估计值(虽然我没有审查,所以这是等效的......我相信)。

survcurv <- function(surv.time, group = NA) {
    #Must be able to coerce surv.time and group to vectors
    if(!is.vector(as.vector(surv.time)) | !is.vector(as.vector(group))) {stop("surv.time and group must be coercible to vectors.")}

    #Make sure that the surv.time is numeric
    if(!is.numeric(surv.time)) {stop("Survival times must be numeric.")}

    #Group can be just about anything, but must be the same length as surv.time
    if(length(surv.time) != length(group)) {stop("The vectors passed to the surv.time and group arguments must be of equal length.")}

    #What is the maximum number of ticks recorded?
    max.time <- max(surv.time)  

    #What is the number of groups in the data?
    n.groups <- length(unique(group))

    #Use the number of ticks (plus one for t = 0) times the number of groups to
    #create an empty skeleton of the results.
    curves <- data.frame(tick = rep(0:max.time, n.groups), group = NA, surv.prop = NA)

    #Add the group names - R will reuse the vector so that equal numbers of rows
    #are labeled with each group.
    curves$group <- unique(group)

    #For each row, calculate the number of survivors in group[i] at tick[i]
    for(i in seq_len(nrow(curves))){
      curves$surv.prop[i] <- sum(surv.time[group %in% curves$group[i]] > curves$tick[i]) /
          length(surv.time[group %in% curves$group[i]])
    }

  #Return the results, ordered by group and tick - easier for humans to read.
  return(curves[order(curves$group, curves$tick), ])   

}

I started out following almost exactly the approach you use in your updated answer. But the thing that's irritating about the survfit is that it only marks the changes, not each tick - e.g., it will give you 0 - 100%, 3 - 88% instead of 0 - 100%, 1 - 100%, 2 - 100%, 3 - 88%. If you feed that into ggplot, your lines will slope from 0 to 3, rather than remaining flat and dropping straight down at 3. That might be fine depending on your application and assumptions, but it's not the classic KM plot. This is how I handled the varying numbers of strata:

groupvec <- c()
for(i in seq_along(x$strata)){
    groupvec <- append(groupvec, rep(x = names(x$strata[i]), times = x$strata[i]))
}
f$strata <- groupvec

For what it's worth, this is how I ended up doing it - but this isn't really a KM plot, either, because I'm not calculating out the KM estimate per se (although I have no censoring, so this is equivalent... I believe).

survcurv <- function(surv.time, group = NA) {
    #Must be able to coerce surv.time and group to vectors
    if(!is.vector(as.vector(surv.time)) | !is.vector(as.vector(group))) {stop("surv.time and group must be coercible to vectors.")}

    #Make sure that the surv.time is numeric
    if(!is.numeric(surv.time)) {stop("Survival times must be numeric.")}

    #Group can be just about anything, but must be the same length as surv.time
    if(length(surv.time) != length(group)) {stop("The vectors passed to the surv.time and group arguments must be of equal length.")}

    #What is the maximum number of ticks recorded?
    max.time <- max(surv.time)  

    #What is the number of groups in the data?
    n.groups <- length(unique(group))

    #Use the number of ticks (plus one for t = 0) times the number of groups to
    #create an empty skeleton of the results.
    curves <- data.frame(tick = rep(0:max.time, n.groups), group = NA, surv.prop = NA)

    #Add the group names - R will reuse the vector so that equal numbers of rows
    #are labeled with each group.
    curves$group <- unique(group)

    #For each row, calculate the number of survivors in group[i] at tick[i]
    for(i in seq_len(nrow(curves))){
      curves$surv.prop[i] <- sum(surv.time[group %in% curves$group[i]] > curves$tick[i]) /
          length(surv.time[group %in% curves$group[i]])
    }

  #Return the results, ordered by group and tick - easier for humans to read.
  return(curves[order(curves$group, curves$tick), ])   

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文