我正在尝试制作一个简单的 Shiny ap 来创建 kaplan-meier 生存曲线,这些曲线通过用户所做的选择进行分层。当我对 KM 计算进行静态编码(使用列名 thorTr)时,它可以工作,但计算和绘图是静态的。当我用 input$s 替换时,我得到 ERROR:variable lengths different (found for 'input$s')
我试过查看其他使用 as.formula 和粘贴的代码,但我不明白并且无法开始工作。但我是 R 和 Shiny 的新用户,所以也许我没有做对。这是一个类似的 Shiny ap,但我想使用 survminer 和 ggsurvplot 进行绘图
library(shiny)
library(ggplot2)
library(survival)
library(survminer)
#load data
data(GBSG2, package = "TH.data")
#Define UI for application that plots stratified km curves
ui <- fluidPage(
# Sidebar layout with a input and output definitions
sidebarLayout(
# Inputs
sidebarPanel(
# Select variable strat
selectInput(inputId = "s",
label = "Select Stratification Variable:",
choices = c("horTh","menostat","tgrade"),
selected = "horTh")
),
# Outputs
mainPanel(
plotOutput(outputId = "km")
)
)
)
# Define server function required to create the km plot
server <- function(input, output) {
# Create the km plot object the plotOutput function is expecting
output$km <- renderPlot({
#calc KM estimate with a hard coded variables - the following line works but obviously is not reactive
#km <- survfit(Surv(time,cens) ~ horTh,data=GBSG2)
#replaced hard coded horTh selection with the respnse from the selection and I get an error
km <- survfit(Surv(time,cens) ~ input$s ,data=GBSG2)
#plot km
ggsurvplot(km)
})
}
# Create a Shiny app object
shinyApp(ui = ui, server = server)
我希望有一个图来更新用户选择的分层变量
最佳答案
两件事情:
survfit()
需要明确定义。传递给 survfit()
的对象在原始代码中使用函数右侧的字符值。这会引发错误,我们可以通过将整个粘贴值转换为公式来解决该错误,即 as.formula(paste('Surv(time,cens) ~',input$s))
ggsurvplot()
的调用中定义以避免范围界定问题。这有点技术性,与 ggsurvplot()
的方式有关。被编程。基本上,ggsurvplot()
无法访问在其自身调用之外定义的公式。 尝试更换
km <- survfit(Surv(time,cens) ~ input$s ,data=GBSG2)
ggsurvplot(km)
和
ggsurvplot(survfit(as.formula(paste('Surv(time,cens) ~',input$s)),data=GBSG2))
关于r - 如何修复 R Shiny 中的 'Error: variable lengths differ (found for ' input$s')',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058769/