【发布时间】:2015-12-15 10:13:55
【问题描述】:
可重现的例子:
server.R
library(shiny)
shinyServer( function(input, output, session) {
myDf <- reactiveValues(myData = NULL)
problematicDf <- reactiveValues(test = NULL)
observeEvent(input$myButton, {
myDf$myData <- df
})
observe({
output$myTestUi <- renderUI({
selectInput(inputId = 'mySelection',
label = 'Selection',
choices = levels(myDf$myData$z),
multiple = T,
selected = c(levels(myDf$myData$z)[1])
)
})
})
observe({
problematicDf$test <- subset(myDf$myData, ((myDf$myData$z %in% input$mySelection)))
})
observe({
str(problematicDf$test)
})
observe({
as.matrix(x = problematicDf$test)
})
})
ui.R
library(shiny)
shinyUI( bootstrapPage(
h3("Push the button"),
actionButton(inputId = "myButton",
label = "clickMe"),
h4("Split Merkmal"),
uiOutput("myTestUi")
))
global.R
df <- data.frame(x = 1:10, y = 10:1, z = letters[1:10])
df$z <- as.factor(df$z)
这给了我:
NULL
[1] "NULL"
NULL
Warning: Unhandled error in observer: 'data' must be of a vector type, was 'NULL'
observe({
as.matrix(x = problematicDf$test)
})
只看
的输出observe({
str(problematicDf$test)
print(class(problematicDf$test))
print(problematicDf$test$z)
})
点击action Button后,没有as.matrix,我得到:
NULL
[1] "NULL"
NULL
'data.frame': 0 obs. of 3 variables:
$ x: int
$ y: int
$ z: Factor w/ 10 levels "a","b","c","d",..:
[1] "data.frame"
factor(0)
Levels: a b c d e f g h i j
'data.frame': 1 obs. of 3 variables:
$ x: int 1
$ y: int 10
$ z: Factor w/ 10 levels "a","b","c","d",..: 1
[1] "data.frame"
[1] a
Levels: a b c d e f g h i j
这是有问题的。正如你所看到的,它首先创建了一个df,它有点空,带有占位符,class = NULL。然后,它填补了这一点。但是,似乎其他reactive functions 正在等待创建problematicDf$test,尽快 创建空df(使用class = NULL)。他们之后不再更新。它们仅在进行另一个选择时更新。
这会导致(在我的情况下)程序崩溃,因为我需要使用如此创建的 data.frame 继续工作和子集等。
如何处理?!
我可以包含if else 并检查class = NULL。但在我看来,这是一种不雅的方式。
【问题讨论】:
标签: r shiny reactive-programming