R - 使用可操作包在 Shiny 上编辑多个数据框



我是闪亮的新手,我想通过单选按钮或使用 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 的下拉列表时,它没有显示数据帧。 请指教。

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

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)

最新更新