在Shiny中,使用来自用户输入的新值更新DataTable [英] In Shiny, update DataTable with new values from user input

查看:141
本文介绍了在Shiny中,使用来自用户输入的新值更新DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个闪亮的应用程序,该应用程序具有一个表(使用 DT :: renderDataTable ),用户可以从中选择一行。但是我希望用户也可以在表中尚未添加新行的情况下添加新行。我正在使用输入控件供用户输入新数据,并且有一个操作按钮,如果按下该按钮,则应根据输入值在表格中创建新的数据行。但是按下按钮不会更新表格。

I'm writing a shiny app that has a table (using DT::renderDataTable) from which users can select a row. But I want the user to also be able to add new row(s) if what they want is not already in the table. I'm using input controls for the user to enter new data, and I have an action button which, if pressed, should create a new row of data in the table from the input values. But pressing the button does not update the table.

一个简单的例子:

library(shiny)
library(DT)
mydata = data.frame(id=letters[1:5], val=sample(10,5,T))

ui = fluidPage(dataTableOutput("table"),
               textInput('NewID', 'Enter new ID'),
               numericInput('NewVal', 'Enter new val', 1),
               actionButton("goButton", "Update Table"))

server = function(input,output){
  output$table = renderDataTable(mydata)
  update = eventReactive(input$goButton, {
    newrow = data.frame(id = input$NewID, val = input$NewVal)
    mydata = rbind(mydata, newrow)
  })
}

shinyApp(ui,server)

很明显,这是解决这个问题的错误方法。我尝试了包装 renderDataTable 和更新 renderUI中的 mydata 的代码的各种组合观察反应性,但是我找不到正确的方法

Clearly, this is the wrong way to approach this. I've tried various combinations of wrapping both renderDataTable and the code to update mydata inside renderUI, observe and reactive, but I can't find the right way to do this.

这是我的第一个闪亮应用程序,所以也许有一个基本概念我不太了解。正确的方法是什么?

This is my first shiny app, so maybe there is a basic concept that I'm not quite grasping. What is the right way?

推荐答案

您可以呈现 eventReactive ,您将在其中返回更新的数据集。别忘了使用<-来修改全局数据集:

You can render the result of eventReactive, where you return the updated dataset. Don't forget to use <<- to modify the global dataset as well:

server = function(input,output){
  output$table <- renderDataTable( df())
  df <- eventReactive(input$goButton, {
    if(input$NewID!="" && !is.null(input$NewVal) && input$goButton>0){
      newrow = data.table(id = input$NewID,
                        val = input$NewVal)
      mydata <<- rbind(mydata, newrow)
      }
    mydata
  }, ignoreNULL = FALSE)
}

这篇关于在Shiny中,使用来自用户输入的新值更新DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆