在下面的玩具示例中,我有两个数据集df1和df2.使用闪亮和rhandsontable将数据集输出到交互式表.我的问题是,如果用户没有在闪亮的应用程序中编辑数据集,输出$ out只识别数据集的变化,如is.null(输入$ out)所示.
当输入$ out不为null时,当输入$ 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)
Run Code Online (Sandbox Code Playgroud)
您可以使用它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
})
}
Run Code Online (Sandbox Code Playgroud)
更改表时,正确df1或df2更新了无功值.在观察者中,它input$df是隔离的,这样代码的这一部分只对用户更改表时作出反应.
| 归档时间: |
|
| 查看次数: |
3547 次 |
| 最近记录: |