在下面的玩具示例中,我有两个数据集 df1 和 df2。使用shiny & rhandsontable 将数据集输出到交互式表格。我的问题是,如果用户没有像 is.null(input$out) 所指示的那样编辑 Shiny 的应用程序中的数据集,则 output$out 仅识别数据集的变化。
当 input$out 不为空时 input$df 更改时,如何修复以下代码以加载 df1 或 df2?
require(rhandsontable)
require(shiny)
df1 <- data.frame(col1 = rnorm(20),
col2 = rep(T, 20))
df2 <- data.frame(col1 = rnorm(20),
col2 = rep(F, 20))
funcX <- function(x) {
x$out <- ifelse(x$col2 == T, x$col1 * 1.5, x$col1)
x$out
}
df2$out <- funcX(df2)
df1$out <- funcX(df1)
server <- function(input, output) {
df <- reactive({
if (input$df == "df1") {
df <- df1
} else {
df <- df2
}
df
})
output$out <- renderRHandsontable({
if (is.null(input$out)) {
hot <- rhandsontable(df())
} else {
str(input$out)
hot <- hot_to_r(input$out)
hot$out <- funcX(hot)
hot <- rhandsontable(hot)
}
hot
})
}
ui <- fluidPage(sidebarLayout(sidebarPanel(
selectInput(
'df', 'Select data.frame:',
choices = c('df1', 'df2'),
selected = 'df1'
)
),
mainPanel(rHandsontableOutput("out"))))
shinyApp(ui = ui, server = server)
最佳答案
您可以使用 reactiveValues
存储 df1
和 df2
数据框,并在修改这些值时更新这些值。这是一个例子 server.R
代码:
server <- function(input, output) {
values = reactiveValues()
values[["df1"]] <- df1
values[["df2"]] <- df2
observe({
if (!is.null(input$out)) {
temp <- hot_to_r(input$out)
temp$out <- funcX(temp)
if (isolate(input$df) == "df1") {
values[["df1"]] <- temp
} else {
values[["df2"]] <- temp
}
}
})
df <- reactive({
if (input$df == "df1") {
df <- values[["df1"]]
} else {
df <- values[["df2"]]
}
df
})
output$out <- renderRHandsontable({
hot <- rhandsontable(df())
hot
})
}
换表时,正确
df1
或 df2
在 react 值中更新。在观察者中,input$df
是隔离的,因此这部分代码仅在用户更改表时使用react。
关于r - Shiny:使用 rhandsontable 在响应式(Reactive)数据集之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32292547/