将条目列添加到 r 闪亮数据表的按钮

Mar*_*ark 4 datatable r datacolumn columnheader shiny

我正在寻找一种方法将按钮添加到 r Shiny 中的数据表:每次单击时向数据表添加一个空列(以及首先制作表格的数据框,用户可以用数字或文本值 并设置自己的列名来描述条目值的类型。

例如,将实验室笔记记录手动添加到闪亮的应用程序中已经存在的仪器数据中

我在问,如果一个比我有更好线索的更熟练的人知道如何做到这一点。我已经阅读了一堆页面,但我发现的示例充其量提供了 1 个具有固定名称的固定空列

空列

包中的虚拟表:library(DT)

ui <- basicPage(
  h2("The mtcars data"),
  DT::dataTableOutput("mytable")
)

server <- function(input, output) {
  output$mytable = DT::renderDataTable({
    mtcars
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

dww*_*dww 5

您可以使用按钮将新列添加到 R 闪亮数据表中,如下所示:

ui <- fluidPage(
  h2("The mtcars data"),
  DT::dataTableOutput("mytable"),
  textInput('NewCol', 'Enter new column name'),
  radioButtons("type", "Column type:",
               c("Integer" = "integer",
                 "Floating point" = "numeric",
                 "Text" = "character")),
  actionButton("goButton", "Update Table")
)

server <- function(input, output) {
  mydata <- mtcars
  output$mytable = DT::renderDataTable(df())
  df <- eventReactive(input$goButton, {
    if(input$NewCol!="" && !is.null(input$NewCol) && input$goButton>0){
      if (input$type == "integer") v1 <- integer(NROW(mydata))
      if (input$type == "numeric") v1 <- numeric(NROW(mydata))
      if (input$type == "character") v1 <- character(NROW(mydata))
      newcol <- data.frame(v1)
      names(newcol) <- input$NewCol
      mydata <<- cbind(mydata, newcol)
    }
    mydata
  }, ignoreNULL = FALSE)
}    
shinyApp(ui,server)
Run Code Online (Sandbox Code Playgroud)

如果您还需要以交互方式编辑单元格的内容,则可以使用renderRHandsontable代替renderDataTable。像这样:

library(rhandsontable)

ui <- fluidPage(
  h2("The mtcars data"),
  rHandsontableOutput("mytable"),
  textInput('NewCol', 'Enter new column name'),
  radioButtons("type", "Column type:",
    c("Integer" = "integer",
      "Floating point" = "numeric",
      "Text" = "character")),
  actionButton("goButton", "Update Table")
)

server <- function(input, output) {
  mydata <- mtcars[1:5,]
  output$mytable = renderRHandsontable(df())
  df <- eventReactive(input$goButton, {
    if(input$NewCol!="" && !is.null(input$NewCol) && input$goButton>0){
      if (input$type == "integer") v1 <- integer(NROW(mydata))
      if (input$type == "numeric") v1 <- numeric(NROW(mydata))
      if (input$type == "character") v1 <- character(NROW(mydata))
      newcol <- data.frame(v1)
      names(newcol) <- input$NewCol
      mydata <<- cbind(mydata, newcol)
    }
    rhandsontable(mydata, stretchH = "all")
  }, ignoreNULL = FALSE)
  observe(if (!is.null(input$mytable)) mydata <<- hot_to_r(input$mytable))
}

shinyApp(ui,server)
Run Code Online (Sandbox Code Playgroud)