Reproducable example:
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)
This gives me:
NULL
[1] "NULL"
NULL
Warning: Unhandled error in observer: 'data' must be of a vector type, was 'NULL'
observe({
as.matrix(x = problematicDf$test)
})
Only looking at the output of
observe({
str(problematicDf$test)
print(class(problematicDf$test))
print(problematicDf$test$z)
})
after clicking on the action Button
, without the as.matrix
, I get:
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
That is problematic. As you can see it creates first a df
which is sort of empty, with placeholders, of class = NULL
. And then, it fills this. However, it seems that other reactive functions
, waiting for the problematicDf$test
to be created kick in as soon as the empty df
is created (with class = NULL
). They do not update afterwards anymore. They only update when another selection is made.
This causes (in my case) the program to crash since I need to keep on working and subsetting etc. with the so created data.frame
.
How to handle this?!
I could include an if else
and check for class = NULL
. But it seems to me that this is an unelegant way.