从全局数据对象中随机采样,并在r Shiny的输入选择中使用



感觉这是一个非常简单的问题,我就是想不明白。从本质上讲,我有一个应用程序,我有一个预先存在的数据对象(一个选择列表),从中我随机抽样。然后,我将这些信息用于UI上的输入选择。然后将其中的选择下载为csv文件。有些实用性在这里可能没有意义,这个例子只是为了说明。这是一个表达式:

UI

library(shinyWidgets)
sides <- c("Right", "Left", "Up", "Down") # list of possible choices
sides <- rep(sides,2)
side_tested <- sample(sides,8) # random sample of 8
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
downloadButton("dlData","Download")
),
mainPanel(
radioGroupButtons(
inputId = "ad1",
label = "Correct",
choices = c(side_tested[1], "Yes", "No"), # takes the first value in side_tested list
justified = TRUE
),
radioGroupButtons(
inputId = "ad2",
label = NULL, 
choices = c(side_tested[2], "Yes", "No"), # takes the second value in side_tested list etc etc
justified = TRUE
), 
# note I will have 8 input buttons in the final example matching length of side_tested, keeping short for reprex.
)
)
)

服务器

server <- function(input, output, session) {
ad_results <- reactive({
c(input$ad1, input$ad2)
})
results <- reactive({
data.frame(cbind(side_tested,ad_results()))
})
output$dlData <- downloadHandler(
filename = ("Results.csv"),
content = function(file){
write.csv(results(), file, row.names=TRUE)
})
}

我的问题是:

  • 当发布这个应用程序的样本不是随机的每次启动应用程序(即选择是相同的每次加载应用程序)。我对此的理解是因为side_tested是在全局环境中,并不是每次都采样。

我已经尝试将采样添加到服务器和ui中,但无法使其工作。我想到的一个解决方案是让ui成为一个函数,在这个想法的帮助下,像这样

ui <- function(req) { 
side_tested <- sample(sides,8)
# ... rest of app here
  • 这解决了随机化问题,但然后我的下载按钮不再工作。

如果有人能帮我指出正确的方向,那就太好了!!谢谢你!

尝试在服务器端取样并使用updateRadioGroupButtons()。也许这能满足你的需要。

library(shinyWidgets)
sides <- c("Right", "Left", "Up", "Down") # list of possible choices
sides <- rep(sides,22)
# side_tested <- sample(sides,8) # random sample of 8
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
downloadButton("dlData","Download")
),
mainPanel(

radioGroupButtons(
inputId = "ad1",
label = "Correct",
choices = c("Yes", "No"), # takes the first value in side_tested list
justified = TRUE
),
radioGroupButtons(
inputId = "ad2",
label = NULL, 
choices = c("Yes", "No"), # takes the second value in side_tested list etc etc
justified = TRUE
) 
# note I will have 8 input buttons in the final example matching length of side_tested, keeping short for reprex.
)
)
)
server <- function(input, output, session) {

side_tested <- sample(sides,8) # random sample of 8

updateRadioGroupButtons(session, "ad1", choices = c(side_tested[1], "Yes", "No"))
updateRadioGroupButtons(session, "ad2", choices = c(side_tested[2], "Yes", "No"))



ad_results <- reactive({
c(input$ad1, input$ad2)
})

results <- reactive({
data.frame(cbind(side_tested,ad_results()))
})

output$dlData <- downloadHandler(
filename = ("Results.csv"),
content = function(file){
write.csv(results(), file, row.names=TRUE)
})

}
shinyApp(ui, server)

最新更新