我已经构建了一个Shiny应用程序,该应用程序提示用户输入作为行动态添加到rHandsontable的输入。用户可以添加行,对其进行编辑,然后添加更多行。该应用程序按其应有的方式工作,除了创建为hot_col
且类型='dropdown'的列。在下一次添加行时,不会保留用户对这些列所做的任何编辑,而所有其他编辑都将保留。
下面是我的应用。保留对word
列的编辑,但不保留对color
创建的hot_col()
列的编辑。
library(shiny)
library(rhandsontable)
library(dplyr)
ui <- fluidPage(
fluidRow(
textAreaInput('wordlines', "Enter words separated by newlines"),
actionButton('submit', "Submit Words"),
rHandsontableOutput('hot')
)
)
server <- function(input, output, session) {
colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet")
build_df <- function(input) {
data.frame(
word = unlist(strsplit(input$wordlines, "\n")),
number = sample(100, 1),
color = NA,
stringsAsFactors = FALSE
)
}
values <- reactiveValues()
observeEvent(input$submit, {
req(input$wordlines)
if(input$submit == 1) { # if button pressed the first time
values$df <- build_df(input)
} else {
tmp <- hot_to_r(input$hot)
values$df <- bind_rows(tmp, build_df(input)) # add new rows to values$DF
}
updateTextAreaInput(session, 'wordlines', value = "") # clear textAreaInput
output$hot <- renderRHandsontable({
rhandsontable(values$df, overflow = 'visible') %>% hot_col(col = "color", type = "dropdown", source = colors) # dropdown column which, when edited, should preserve those edits through future adding of rows ('submit' button presses)
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
答案 0 :(得分:0)
您应该调整两点:
render*
函数包装在observeEvent
中是不好的做法这是您代码的有效版本:
library(shiny)
library(rhandsontable)
library(dplyr)
ui <- fluidPage(
fluidRow(
textAreaInput('wordlines', "Enter words separated by newlines"),
actionButton('submit', "Submit Words"),
p(),
rHandsontableOutput('hot')
)
)
server <- function(input, output, session) {
colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet")
build_df <- function(input) {
data.frame(
word = unlist(strsplit(input$wordlines, "\n")),
number = sample(100, 1),
color = NA_character_,
stringsAsFactors = FALSE
)
}
values <- reactiveValues()
observeEvent(input$submit, {
req(input$wordlines)
if(input$submit == 1) { # if button pressed the first time
values$df <- build_df(input)
} else {
tmp <- hot_to_r(input$hot)
values$df <- bind_rows(tmp, build_df(input)) # add new rows to values$DF
}
updateTextAreaInput(session, 'wordlines', value = "") # clear textAreaInput
})
output$hot <- renderRHandsontable({
req(values$df)
rhandsontable(values$df, overflow = 'visible') %>% hot_col(col = "color", type = "dropdown", source = colors) # dropdown column which, when edited, should preserve those edits through future adding of rows ('submit' button presses)
})
}
# Run the application
shinyApp(ui = ui, server = server)