sliderInput values as dataframe in shiny
Sophia Terry
in course of an experiment I am trying to build in shiny I would like to print a .csv including values from different sliderInputs. Therefore I want to use them as dataframe. I included a shortened example of what I am trying to do below.
However, if I run the code as below it returns
Do you need to wrap inside reactive() or observer()?
If I do wrap the inputs into reactive() however it returns
cannot coerce class ‘c("reactiveExpr", "reactive", "function")’ to a data.frame
Does anyone have a solution to this?
library(shiny)
ui <- fluidPage( br(), sliderInput(inputId = "S1", label= "S1", min = 1, max = 10, value = 5), br(), sliderInput(inputId = "S2", label= "S2", min = 1, max = 10, value = 5), br(), plotOutput("P1", width = "40vw"), actionButton("printData", "Print")
)
server <- function(input, output) { data <- reactive({ c(input$S1, input$S2) }) data1 <- c(input$S1) data2 <- c(input$S2) dataframe <-data.frame(Column1 = c(data1, data2)) output$P1 <- renderPlot({ barplot(data(), horiz=TRUE, names.arg=c("S2", "S1"), xlim = c(0,10)) }) observeEvent(input$printData, { write.csv2(dataframe, "test.csv", row.names = TRUE) })
}
shinyApp(ui = ui, server = server) 1 Answer
This works:
library(shiny)
ui <- fluidPage( br(), sliderInput(inputId = "S1", label= "S1", min = 1, max = 10, value = 5), br(), sliderInput(inputId = "S2", label= "S2", min = 1, max = 10, value = 5), br(), plotOutput("P1", width = "40vw"), actionButton("printData", "Print")
)
server <- function(input, output) { data <- reactive({ data.frame(Column1 = c(input$S1, input$S2)) }) output$P1 <- renderPlot({ barplot(data()[["Column1"]], horiz=TRUE, names.arg=c("S1", "S2"), xlim = c(0,10)) }) observeEvent(input$printData, { write.csv2(data(), "test.csv", row.names = TRUE) })
}
shinyApp(ui, server)If you're just starting out with Shiny you can try reading this: , which is really helpful.
input values are reactive. You've assigned them using reactive to data, so it is not clear why you are then assigning them individually to data1 and data2. You won't be able to do that because then you are trying to do something with reactives outside of a reactive context. This then means you can't create dataframe. In my example, I create a data frame using reactive, which I then call in my renderer and observer - note that to use reactives, you need to call them using ().