簡體   English   中英

如何使用操作按鈕向 R Shiny 中使用 rhandsontable 呈現的數據框添加列?

[英]How to add columns to a data frame rendered with rhandsontable in R Shiny with an action button?

我正在努力通過操作按鈕將列添加到通過 rhandsontable package 呈現的數據框(出於以后的格式化原因,我需要使用操作按鈕來添加列而不是依賴 rhandsontable 的上下文菜單)。 下面的代碼幾乎可以正常工作,但我每第二次點擊“添加”操作按鈕都會得到奇怪的結果。 可能是由於我不完全理解點擊計數器的工作原理,在...if(input$addCol > 0){testDF}... 無論如何,每次單擊“添加”都應該向呈現的表添加一列(默認值為 1、2、3),並且用戶必須能夠手動覆蓋默認值,並通過進一步的添加單擊保留這些修改后的值。 下面的圖片解釋得更好,代碼在底部。

我怎樣才能修復下面的代碼,使其按預期工作? 單擊“添加”添加一列,並保留對表的手動更改?

在此處輸入圖像描述

在此處輸入圖像描述

代碼:

library(shiny)
library(rhandsontable)

myDF <- data.frame(x = c(1,2,3))

ui <- fluidPage(
  rHandsontableOutput('hottable'),br(),
  actionButton('addCol','Add')
)

server <- function(input, output, session) {
  
  observe({myDFOut <<- print(hot_to_r(input$hottable))})
  
  output$hottable <- renderRHandsontable({
    rhandsontable(if(input$addCol > 0){testDF} else {myDF})
  })

  observeEvent(input$addCol,{
    newCol <- data.frame(c(1,2,3))
    names(newCol) <- paste("Col",ncol(hot_to_r(input$hottable))+1)
    testDF <<- cbind(hot_to_r(input$hottable),newCol)
  })
  
}

shinyApp(ui, server)

嘗試使用reactiveVal (關於 function here )。

library(shiny)
library(rhandsontable)

myDF <- data.frame(x = c(1, 2, 3))

ui <- fluidPage(rHandsontableOutput('hottable'),
                br(),
                actionButton('addCol', 'Add'))

server <- function(input, output, session) {
  EmptyTbl <- reactiveVal(myDF)
  
  observeEvent(input$hottable, {
    EmptyTbl(hot_to_r(input$hottable))
  })
  
  output$hottable <- renderRHandsontable({
    rhandsontable(EmptyTbl())
  })
  
  observeEvent(input$addCol, {
    newCol <- data.frame(c(1, 2, 3))
    names(newCol) <- paste("Col", ncol(hot_to_r(input$hottable)) + 1)
    EmptyTbl(cbind(EmptyTbl(), newCol))
    
  })
  
}

shinyApp(ui, server)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM