使用rhandsontable包来编辑闪亮的多个数据框

时间:2018-01-10 14:17:22

标签: r shiny shiny-server shinyjs rhandsontable

我是闪亮的新手,我想通过单选按钮编辑不同的多个数据帧或使用rhandsontable包选择输入。但是,我的脚本无法显示其他数据框,只能显示第一个,我不知道问题是什么。

ui.R:
library(rhandsontable)
fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select2", label = h3("Choose to edit"), 
              choices = list("003.csv", "004.csv", "005.csv", 
                             "006.csv", "007.csv"), 
              selected = "003.csv"),
  actionButton("saveBtn", "Save changes")
),
mainPanel(
  rHandsontableOutput("hot")
)))

server.R
values <- reactiveValues() 
setHot <- function(x) values[["hot"]] <<- x 
function(input, output, session) {

 fname <- reactive({
   x <- input$select2
   return(x)
 })

 observe({ 
   input$saveBtn # update csv file each time the button is pressed
   if (!is.null(values[["hot"]])) { 
  write.csv(x = values[["hot"]], file = fname(), row.names = FALSE)
}
})

 output$hot <- renderRHandsontable({ 
   if (!is.null(input$hot)) { # if there is an rhot user input...
  DF <- hot_to_r(input$hot) # convert rhandsontable data to R object 
  and store in data frame
  setHot(DF) # set the rhandsontable values

} else {
  DF <- read.csv(fname(), stringsAsFactors = FALSE) # else pull table from the csv (default)
  setHot(DF) # set the rhandsontable values
}

rhandsontable(DF) %>% # actual rhandsontable object
  hot_table(highlightCol = TRUE, highlightRow = TRUE, readOnly = TRUE) %>%
  hot_col("Status", readOnly = FALSE)
 })}

我可以编辑并保存显示第一个003.csv的数据帧,但是当我使用下拉列表004.csv时,它没有显示数据帧。请指教。

1 个答案:

答案 0 :(得分:1)

这将写入(并可能覆盖任何现有文件)虚拟数据:

for (i in c("003.csv", "004.csv", "005.csv", "006.csv", "007.csv")) {
  write.csv(cbind(V1 = rep(i, 3), Status = "foo"), i, row.names = FALSE)
}

我对server进行了大修:

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(
        "select2", label = h3("Choose to edit"), selected = "003.csv",
        choices = list("003.csv", "004.csv", "005.csv", "006.csv", "007.csv")
      ),
      actionButton("saveBtn", "Save changes")
    ),
    mainPanel(
      rHandsontableOutput("hot")
    )
  )
)

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

  DF <- reactiveVal()

  observe({
    DF(read.csv(input$select2, stringsAsFactors = FALSE))
  })

  observe({
    if (!is.null(input$hot)) DF(hot_to_r(input$hot))
  })

  observeEvent(input$saveBtn, {
    if (!is.null(DF())) write.csv(DF(), input$select2, row.names = FALSE)
  })

  output$hot <- renderRHandsontable({
    rhandsontable(DF()) %>% 
      hot_table(highlightCol = TRUE, highlightRow = TRUE, readOnly = TRUE) %>%
      hot_col("Status", readOnly = FALSE)
  })

}

shinyApp(ui, server)