I can't filter a reactive dataset. I need to call different datasets on my pc according to the user input; since those datasets have the same row names I want to define a single filter for them.
For this question I made two simple datasets. Thank you so much in advance.
UI
library(shiny)
ui <- fluidPage(
sidebarLayout(sidebarPanel(selectInput('number', h4("Select number"),
choices = c("first", "second")),
selectInput('dataset', h4("Select dataset"),
choices=c("dataset1",
"dataset2"))),
mainPanel(
plotOutput("graph")
)))
SERVER
server <- function(input, output) {
library(ggplot2)
library(dplyr)
dataset1 <- data.frame(names=c("first", "second"),
X1=rnorm(1:10),X2=rnorm(1:10),X3=rnorm(1:10))
dataset2 <- data.frame(names=c("first", "second"),
X1=rnorm(1:10),X2=rnorm(1:10),X3=rnorm(1:10))
plotdata <- reactive ({get(input$dataset)
if(input$number == "first") {
filter(plotdata, names=="first")}
else if(input$number == "second") {
filter(plotdata, names=="second")}
})
output$graph <- renderPlot({
datos <- plotdata()
ggplot(datos, aes(X1, X2)) +
geom_col()
})
}
shinyApp(ui = ui, server = server)
I get the following Error: no applicable method for 'filter_' applied to an object of class "c('reactiveExpr', 'reactive')"
However, when the reactive data section is replaced by the following code, it makes the graph without issues but I would have to define all possible combinations between variables and datasets (which is not an option since the real datasets are 5 with lots of variables and rows to be selected on the UI):
plotdata <- reactive ({
if(input$number == "first") {
filter(dataset1, names=="first")}
else if(input$number == "second") {
filter(dataset1, names=="second")}
})
So how can I filter from a reactive dataset using dplyr??
You can do that like this:
library(shiny)
ui <- fluidPage(
sidebarLayout(sidebarPanel(selectInput('number', h4("Select number"),
choices = c("first", "second")),
selectInput('dataset', h4("Select dataset"),
choices=c("dataset1",
"dataset2"))),
mainPanel(
plotOutput("graph")
))
)
server <- function(input, output) {
library(ggplot2)
library(dplyr)
dataset1 <- data.frame(names=c("first", "second"),
X1=rnorm(1:10),X2=rnorm(1:10),X3=rnorm(1:10))
dataset2 <- data.frame(names=c("first", "second"),
X1=rnorm(1:10),X2=rnorm(1:10),X3=rnorm(1:10))
plotdata <- reactive ({
dataset <- get(input$dataset)
dataset %>% filter(names==input$number)
})
output$graph <- renderPlot({
datos <- plotdata()
ggplot(datos, aes(X1, X2)) +
geom_col()
})
}
shinyApp(ui = ui, server = server)
However, my advice is to not use get
, but store your datasets in a named list, so something like datasets <- list('dataset1'=1, 'dataset2'=2)
and then call with datasets[[input$dataset]]
Hope this helps!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments