gpt4 book ai didi

在 renderPlot 中找不到 R Shiny 对象

转载 作者:行者123 更新时间:2023-12-05 04:06:16 26 4
gpt4 key购买 nike

我在 renderPlot(shiny) 函数中定义了“Time”。但是,我得到一个

Error: object 'Time' not found.

我想知道为什么我会收到这个错误已经为“时间”变量定义

library(shiny)
library(survival)
library(survminer)
library(ggplot2)

ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file","File input"),

selectInput("Survival",
label = "Survival",
choices = c('time.day',
'time.year'),
selected = 'time.day'),
selectInput("Treatment",
"Treatment",
choices = c("trt"),
selected = "trt")
),
mainPanel(
plotOutput("KM")
)
)
)

server <- function(input, output) {
output$KM <- renderPlot({
req(input$file)
df <- read.csv(input$file$datapath)
df<- data.frame(df)
Time <- switch(input$Survival,
"time.day" = df$time.day,
"time.year" = df$time.yr)
x <- switch(input$Treatment,
"trt" = df$trt)

fit <- survfit(Surv(Time , cen) ~ x , data = df)
ggsurvplot(fit,risk.table = TRUE)
}
)
}

shinyApp(ui = ui, server = server)

输入数据通常是一个 csv 文件,例如:

 time.yr       time.day     cen  trt
1.181940686 431.7038355 0 1
3.174982816 1159.662473 1 1

最佳答案

事实证明这是一个棘手的问题。通常我们会建议一些非标准的评估来创建 fit 但似乎 ggsurvplot 是挑剔的,它更容易创建您需要的确切数据框:

library(shiny)
library(survival)
library(survminer)
library(ggplot2)

ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file","File input"),

selectInput("Survival",
label = "Survival",
choices = c('time.day',
'time.year'),
selected = 'time.day'),

selectInput("Treatment",
"Treatment",
choices = c("trt"),
selected = "trt")
),
mainPanel(
plotOutput("KM")
)
)
)

server <- function(input, output) {

raw_surv_data <- reactive({
req(input$file)
read.csv(input$file$datapath)
})

surv_data <- reactive({
raw_surv <- raw_surv_data()
data.frame(
Time = raw_surv[[input$Survival]],
x = raw_surv[[input$Treatment]],
cen = raw_surv[['cen']]
)
})

surv_fit <- reactive({
survfit(Surv(Time , cen) ~ x , data = surv_data())
})

output$KM <- renderPlot({
ggsurvplot(surv_fit(), risk.table = TRUE, data = surv_data())
})
}

shinyApp(ui = ui, server = server)

enter image description here

关于在 renderPlot 中找不到 R Shiny 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50057428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com