r - Shiny 每次按下按钮都会生成随机值

标签 r shiny

我是 Shiny 的新手,做了简单的 Shiny 应用程序,它生成 iid 法线变量并打印直方图。 输入有:

  • 2 个数字输入字段,mu 和 sigma
  • 操作按钮

输出为tabsetPanel:

  • 选项卡 1:5 个生成值
  • Tab2:直方图

所以它不起作用。我尝试了很多变体,但唯一有效的解决方案就是这个。

这是代码 ui.R

library(shiny)
library(xtable)

meanInput1 <- numericInput("id1", "$$mean \\ of \\ x_1$$", 1, min = -10, max = 10, step = 1)
meanInput2 <- numericInput("id2", "$$sd \\ of \\ x_2$$", 1, min = -10, max = 10, step = 1)
tabPanel1 <- tabPanel("generated values", tableOutput("table1"))
tabPanel2 <- tabPanel("Plot", plotOutput("plot1"))

shinyUI(fluidPage(
    withMathJax(),
    titlePanel("title"),

    sidebarLayout(
        fluid=TRUE,

        sidebarPanel(
            meanInput1,
            meanInput2,
            actionButton("goButton", "Go!")
        ),
    mainPanel(

        tabsetPanel(
            tabPanel1,
            tabPanel2
        )
    )
)))

这是代码服务器。R

shinyServer(
    function(input, output) {

        output$plot1 <- renderPlot({
            if (input$goButton >= 1){
                sigma <- input$id2
                muInput <- input$id1

                table <- as.data.frame(rnorm(n = 5,muInput,sd = sigma))
                names(table) <- "x"

                output$plot1 <- renderPlot(hist(table));
                output$table1 <- renderTable(head(table));
            }
        })
    }
)

问题:

  • 仅当单击按钮一次并选择 tabPanel2 时,它才有效。如何让它在每次点击按钮时都起作用。

最佳答案

在这种情况下您想使用eventReactive。您可以找到使用 actionButton here 的演示。您的代码结构也有些奇怪,渲染语句内有渲染语句。

如果您创建 eventReactive 函数并将 renderTablerenderPlot 调用分开,它会更清晰并且工作正常。最好不要将变量命名为与函数相同的名称,因此为了清楚起见,我将 table 变量更改为 my_table

shinyServer(
  function(input, output) {

    rand <- eventReactive(input$goButton,{
      sigma <- input$id2
      muInput <- input$id1

      my_table <- as.data.frame(rnorm(n = 5,muInput,sd = sigma))
      names(my_table) <- "x"
      return(my_table)
    })

    output$plot1 <- renderPlot({
      my_table <- rand()
      if(is.null(my_table)){
        return(NULL)
      }else{
        hist(head(my_table$x));
      }
    })


    output$table1 <- renderTable({
      my_table <- rand()

      if(is.null(my_table)){
        return(NULL)
      }else{
        my_table
      }
    });
  }
)

关于r - Shiny 每次按下按钮都会生成随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31548092/

相关文章:

r - 从数据框列表中提取最后一列

在 Shiny 上多个场景的 RSelenium 并发用户

r - 在 Shiny 中格式化sliderInput的数字输出

r - 使用 R 中的plotly 进行 3D 绘图

regex - 使用正则表达式清理日期(特别是年份)

r - 如何将 .Rmd 文件转换为 Rstudio 的 .Rnw 文件?

r - 下载在 Shiny 中创建的表

r - 在Mac OS X中加载rgl软件包时出错

javascript - 交互式数据表 : keep column filters after rerendering the table

r - 未提供错误行号时如何调试?