我构建了一个带有多个选项卡的简单 R 闪亮应用程序。当我运行该应用程序时,当我第一次单击每个选项卡时,每个选项卡上的绘图不会显示。错误消息显示
attempt to select less than one element in get1index
。但是,在我单击每个选项卡直到最后一个选项卡后,每个选项卡上都开始显示图表,并且没有错误消息。顺序并不重要以下是我运行应用程序时的屏幕截图。请您指出我应该朝哪个方向解决这个问题?谢谢,
在单击每个选项卡之前,我收到以下错误消息,并且没有渲染任何绘图。
单击每个选项卡后,从我单击的最后一个选项卡开始,所有绘图开始显示。
R闪亮应用程序的UI和服务器的核心部分提取如下。
ui <- fluidPage(
titlePanel("EMR Comparative Analysis"),
tabsetPanel(
tabPanel("Overall Comparison",
sidebarLayout(
sidebarPanel(
# Radio button to select between EMR Site and EMR Form
radioButtons(
inputId = "overall_comparison_type",
label = "Select comparison type:",
choices = c("EMR Site" = "emrsite", "EMR Form" = "emrform"),
selected = "emrsite"
),
# Dropdown menu for study selection
uiOutput("overallStudySelectInput"),
# Input selection for cumulative daily time series
uiOutput("overallMetricSelectInput")
),
mainPanel(
plotOutput("overallPlot")
)
)
),
tabsetPanel(
tabPanel("Monthly Comparison",
...
}
server <- function(input, output, session) {
...
# Render overall Plot
output$overallPlot <- renderPlot({
data <- selectedData()$overall
print("overall data structure:")
print(str(data))
comparison_var <- if (input$overall_comparison_type == "emrsite") {
"is_emr_site"
} else {
"is_emr_form"
}
comparison_label <- c(
"Yes" = if (input$overall_comparison_type == "emrsite") "EMR Sites" else "EMR Forms",
"No" = if (input$overall_comparison_type == "emrsite") "Non-EMR Sites" else "Non-EMR Forms"
)
data[[comparison_var]] <- factor(data[[comparison_var]], levels = names(comparison_label), labels = comparison_label)
# Identify columns starting with 'ratio' or 'duration_median'
plot_var <- grep("^ratio|^duration_median", names(data), value = TRUE)
ggplot(data, aes_string(x = comparison_var, y = plot_var, fill = comparison_var)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Overall Comparison by Study", x = "EMR vs. Non-EMR", y = "Overall Ratio/Median", fill = "Comparison Group") +
theme_minimal()
})
...
}
# Run App
shinyApp(ui, server)
我已尝试以下更改。
正如您在绘图输出中看到的,存在错误:
尝试在 get1index 中选择少于一个元素
尝试构建
renderPlot()
表达式时会生成此错误。
所以问题与 Shiny 无关。
单击一个选项卡然后返回时行为不同的原因是因为第二次发生某些事情不同。
错误很可能来自这一行:
data[[comparison_var]] <- factor(data[[comparison_var]], levels = names(comparison_label), labels = comparison_label)
例如
LETTERS[[NULL]]
会产生此错误。
我建议检查 init 阶段,此时 input$overall_comparison_type 可能是
NULL
。