我花了大约 2 个小时尝试让这个简单的功能发挥作用。我已经尝试了多种方法,但没有任何进展,所以寻求专家的帮助!
我希望 sliderInput 仅在用户上传 CSV 文件后才显示,并将输入的最大值设置为 CSV 文件中的行数。为了进行测试,我仅使用包含 15 个随机数的 CSV 文件。这看起来很简单,但我无法让它工作。我一直在使用打印对话框来尝试调试,我发现上传工作正常,并且
observeEvents
块打印中的所有打印行均按预期进行,但 renderUI
调用中的打印行永远不会打印。它只是不执行该代码块。为什么?
这是 MRE:
library(shiny)
ui <- fluidPage(
titlePanel("Bootstrap Sample Size Simulator"),
sidebarLayout(
sidebarPanel(
# Define the primary inputs needed to setup the sample size simulation
fileInput("file_upload", "Upload a CSV file with sample data to use for sample size optimization:", accept = ".csv"),
uiOutput("slider_output")
),
mainPanel(
##EMPTY###
)
)
)
#### SERVER ####
server <- function(input, output, session) {
# Create reactive values for the file upload
upload <- reactiveValues(
isUploaded = FALSE, # flag signifying the file has been uploaded
data = NULL # empty placeholder for the data
)
sample_max <- reactive({
NULL # Initially set to NULL
if (is.null(upload$data)) return(NULL) # return NULL if uploadedData is NULL
nrow(upload$data)
})
# define function for the slider UI element for sample size limit selection
slider_ui <- function() {
if (upload$isUploaded()) {
sliderInput("sample_range",
label = "Range of Sample Sizes to simulate from the uploaded data:",
min = 2,
max = sample_max(),
value = c(2, sample_max())
)
} else {
NULL
}
}
# Update reactive values and show slider when file is uploaded
observeEvent(input$file_upload, {
#print("inside observEvent")
upload$isUploaded <- TRUE # Set flag to TRUE after upload
#print(paste("isUploaded:",upload$isUploaded))
upload$data <- read.csv(input$file_upload$datapath) # read the uploaded CSV file
sample_max <- nrow(upload$data) # update sample_max after successful upload
#print(paste("sample_max:",sample_max))
#print(head(upload$data))
})
# Render the slider element conditionally
output$sliderOutput <- reactive({
renderUI({
print("inside RenderUI for sliderOutput")
slider_ui()
})
})
}
#### APP ####
shinyApp(ui = ui, server = server)
有一些问题,查看各个行:
(1) 在 ui 对象中:
uiOutput("slider_output")
应该是 uiOutput("sliderOutput")
这是因为“sliderOutput”是您分配给服务器块内的输出对象的值。
(2) 在 slider_ui 函数中:
if (upload$isUploaded())
应该是 if (upload$isUploaded)
这是因为您使用的是reactiveValues而不是reactiveVal(后者返回一个函数,但前者使用$将其定义的veraibles引用为常规列表)
(3) 在服务器块中:
output$sliderOutput <- reactive({
renderUI({
print("inside RenderUI for sliderOutput")
slider_ui()
})
})
应该是
output$sliderOutput <- renderUI({
print("inside RenderUI for sliderOutput")
slider_ui()
})
“渲染”类函数应分配给服务器的输出对象。而反应式()表达式应分配给您想要使输出或观察者响应的变量。