美文网首页
把你的多因素cox模型做成shinyapp,来一个病人画一个生存

把你的多因素cox模型做成shinyapp,来一个病人画一个生存

作者: 小洁忘了怎么分身 | 来源:发表于2024-04-25 18:05 被阅读0次

0.背景知识

在预后分析中,构建了多因素cox模型后可以选择森林图或者是诺谟图进行可视化。

之前看诺谟图,如果有一个新的病人信息,可以从诺谟图上面自行比划看该新病人的1、3、5年生存率。

这样画起来多少有点麻烦,最近埋头苦读的我发现一个人的生存率也可以做成生存曲线。

1.编造示例数据和构建模型

rm(list = ls())
library(rms)
library(prodlim)
library(survival)
set.seed(13)
ph <- SimSurv(100)
head(ph)

##   eventtime  censtime     time event X1         X2 status
## 1  3.068009 24.716896 3.068009     1  0  0.5543269      1
## 2  9.666322 17.105853 9.666322     1  1 -0.2802719      1
## 3  1.200405  2.101732 1.200405     1  1  1.7751634      1
## 4  2.749020  5.286182 2.749020     1  1  0.1873201      1
## 5  5.974245 14.870069 5.974245     1  0  1.1425261      1
## 6  1.853016  7.541804 1.853016     1  1  0.4155261      1

mod <- cph(Surv(ph$time, ph$event) ~ X1 + X2, data=ph, x=TRUE, y=TRUE, surv=TRUE)

ph里面的X1和X2就是编造的临床信息

2.新来一个病人的话

假如他的临床信息是 X1 = 0,X2 = 1

new_dat <- data.frame(X1 = 0,X2 = 1)

画他的生存曲线

g = survfit(mod,new = new_dat)
dat = data.frame(time = g$time,surv = g$surv)
plot(dat$time, dat$surv, type = "s")

或者是ggplot2版本

library(ggplot2)
ggplot(dat,aes(time,surv))+
  geom_line()+
  theme_bw()

3.更好玩的是可以做成shinyapp

哈哈,看起来很厉害实际上就是唬唬人的东西,有人会用shiny来做很复杂很炫酷的网页工具,我们这个是个入门版本。

rm(list = ls())
library(shiny)
library(rms)
library(prodlim)
library(survival)
# 定义全局模拟数据和模型
simulate_data_and_model <- function() {
  set.seed(13)
  ph <- SimSurv(100)
  mod <- cph(Surv(ph$time, ph$event) ~ X1 + X2, data=ph, x=TRUE, y=TRUE, surv=TRUE)
  return(list(ph = ph, mod = mod))
}

# 调用一次模拟数据和模型,以便在Shiny中使用
data_and_model <- reactive(simulate_data_and_model())

ui <- fluidPage(
  titlePanel("病人生存曲线"),
  sidebarLayout(
    sidebarPanel(
      numericInput("X1", "X1 的值", 0, min = -10, max = 10, step = .1),
      numericInput("X2", "X2 的值", 1, min = -10, max = 10, step = .1),
      actionButton("plotButton", "绘制生存曲线")
    ),
    mainPanel(
      plotOutput("survivalPlot")
    )
  )
)

server <- function(input, output) {

  observeEvent(input$plotButton, {

    new_dat <- data.frame(
      X1 = input$X1,
      X2 = input$X2
    )

    g <- survfit(data_and_model()$mod, new = new_dat)
    dat = data.frame(time = g$time,surv = g$surv)
    library(ggplot2)
    ggplot(dat,aes(time,surv))+
      geom_line()+
      theme_bw()

    output$survivalPlot <- renderPlot({
      ggplot(dat,aes(time,surv))+
        geom_line()+
        theme_bw()
    })
  })
}

shinyApp(ui, server)

然后就有一个酷酷的弹窗可以画图啦


相关文章

网友评论

      本文标题:把你的多因素cox模型做成shinyapp,来一个病人画一个生存

      本文链接:https://www.haomeiwen.com/subject/mwpnxjtx.html