简体   繁体   English

R Shiny:向数据表添加新列

[英]R Shiny: Adding new columns to datatable

I'm using R shiny for creating a machine learning application.我正在使用 R Shiny 来创建机器学习应用程序。 The app uses input widgets to to create the test obsevation, which then gets fed to a randomforest model and output an estimation when an actionbutton is clicked.该应用程序使用输入小部件来创建测试观察,然后将其输入随机森林模型并在单击操作按钮时输出估计值。

I want to store the input data that was selected, as well as the estimation and a timestamp in a datatable.我想将选择的输入数据以及估计值和时间戳存储在数据表中。

I am able to store all the selected input in a table, but I am having some trouble adding the 2 extra columns (estimation and timestamp) to the datatable.我能够将所有选定的输入存储在一个表中,但是我在将 2 个额外的列(估计和时间戳)添加到数据表时遇到了一些麻烦。

Does anyone have an example of how to add new columns to a datatable?有没有人有如何向数据表添加新列的示例? I am using the renderDataTable() and dataTableOutput() function to create the datatable.我正在使用renderDataTable()dataTableOutput()函数来创建数据表。

This is the code for the server functions I found online for creating a datatable from input widgets:这是我在网上找到的用于从输入小部件创建数据表的服务器功能的代码:

server <- function(input, output, session) {

# Create the Log 
  saveData <- function(data) {
    data <- as.data.frame(t(data))
    if (exists("inputparameters")) {
      inputparameters <<- rbind(inputparameters, data)
    } else {
      inputparameters <<- data
    }
  }
  loadData <- function() {
    if (exists("inputparameters")) {
      inputparameters
    }
  }
  
  # Whenever a field is filled, aggregate all form data
  formData <- reactive({
    data <- sapply(fields, function(x) input[[x]])
    data
  })
  
  # When the Submit button is clicked, save the form data
  observeEvent(input$submit, {
    saveData(formData())
  })
  
  # Show the previous responses
  # (update with current response when Submit is clicked)
  output$inputparameters <- DT::renderDataTable({
    input$submit
    loadData()
  })
  
} # End Server function

How do I add new columns to the table in addition to the columns from input widgets?除了来自输入小部件的列之外,如何向表中添加新列?

Thanks in advance, I appreciate all your inputs.提前致谢,感谢您的所有意见。

Here's a solution that I've come up with:这是我想出的解决方案:

library(shiny)
library(DT)

# datatable output function
dt_output = function(title, id) {
  fluidRow(column(
    12, h1(title)), # title
    hr(), DTOutput(id) # datatable output
  )
}
# render datatable function
render_dt = function(data, editable = 'cell', server = TRUE, ...) {
  renderDT(data, selection = 'none', server = server, editable = editable, ...)
}

# user interface
ui = fluidPage(
  
  # add button to add column
  actionButton(inputId = "addColumn", "New Column"),
  
  # custom column name
  textInput(inputId = "nameColumn", "New Column Name"),
  
  # title for page
  title = 'Double-click to edit table cells',
  # datatable output
  dt_output('Add Column Example")', 'x'),
  
  # add button to finish adding column and variables
  actionButton(inputId = "done", "Done"),
)


server <- function(input, output, session) {
  # use iris data as an reproducible example
  data = reactive({iris})
  
  # set up reactive value
  reactiveData = reactiveVal()
  
  # observe data
  observeEvent(data(),{
    reactiveData(data())
  })
  
  # showing only 5 rows per page
  options(DT.options = list(pageLength = 5))
  
  # make cells editable in our data
  output$x = render_dt(reactiveData(), 'cell')
  
  # edit a single cell
  proxy = dataTableProxy('x')
  observeEvent(input$x_cell_edit, {
    info = input$x_cell_edit
    newData <- reactiveData()
    newData[info$row, info$col] <- info$value
    reactiveData(newData)
    replaceData(proxy, reactiveData(), resetPaging = FALSE)
  })
  
  # add a column
  observeEvent(input$addColumn,{
    newData <- reactiveData()
    newData[[input$nameColumn]] <- numeric(length = nrow(newData))
    reactiveData(newData)
    replaceData(proxy, reactiveData(), resetPaging = FALSE)
    output$x = render_dt({
      reactiveData()
    })
  })
  
  # check for 'done' button press
  observeEvent(input$done, {
    stopApp(reactiveData())
  })
  
}

# run Shiny app
shinyApp(ui, server)

Because I don't have access to your data, I've provided a reproducible example using the iris dataset.因为我无权访问您的数据,所以我提供了一个使用 iris 数据集的可重现示例。 I used this DT-edit example as the basis for the app.我使用这个DT-edit 示例作为应用程序的基础。

As @Stéphane Laurent said, it's necessary to re-render the table (see # add a column ).正如@Stéphane Laurent 所说,有必要重新渲染表格(请参阅# add a column )。 The current data does not get lost but there is a glitch with the first value you enter (it resets the value).当前数据不会丢失,但您输入的第一个值会出现故障(它会重置该值)。 After, the first value it will no longer reset.之后,第一个值将不再重置。 I've also provide text input so that the new column can be named.我还提供了文本输入,以便可以命名新列。

示范值输入

After pressing the "Done" button, the data will be output to your R console.按“完成”按钮后,数据将输出到您的 R 控制台。

演示附加列的输出

You can repeatedly press the "Add Column" button to produce columns.您可以反复按“添加列”按钮来生成列。

演示多列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM