Reactive graph dependent on multiple inputs - shiny

I have a reactive graph that takes in multiple inputs but it is dependent on all those inputs. Is there a way that the graph can take all the inputs but it isn't dependent on them all. For example if the user selects one drop down the graph will update and not need any of the other inputs but if the user adds a second input the graph will update with the 2nd input but not need the 3rd unless it is selected. Also if what the user has selected is null it won't change the graph.
UI:
ui <- dashboardPage(
dashboardHeader(title = "Human Trafficking"),
dashboardSidebar(
sidebarMenu(
selectInput("Source", "Choose a Data Source: ", choices = sort(unique(ngo$Data.Provided.By)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
dateInput("startdate", "Start Date:", value = "2009-01-01", format = "dd-mm-yyyy",
min = "2009-01-01", max = "2019-08-26"),
dateInput("enddate", "End Date:", value = "2019-08-27", format = "dd-mm-yyyy",
min = "2009-01-02", max = "2019-08-27"),
selectInput("Nationality", "Select a nation: ", choices = sort(unique(ngo$Victim.Nationality))),
actionButton("button", "Apply")
)
),
dashboardBody(
fluidRow(
box(width = 4, solidHeader = TRUE,
selectInput("traffickingType", "Choose a trafficking type: ", choices = sort(unique(ngo$Trafficking.Type)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("traffickingSubType", "Choose a trafficking sub type: ", choices = sort(unique(ngo$Trafficking.Sub.Type)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("gender", "Choose a gender: ", choices = sort(unique(ngo$Victim.Gender)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
)
),
fluidRow(
box(width = 6, solidHeader = TRUE, status = "primary",
title = "Trafficking Type",
plotlyOutput("coolplot", width = '750px', height = '600px')
),
box(width = 6, solidHeader = TRUE, status = "primary",
title = "Trafficking Sub-Type",
plotlyOutput("Sub", width = '750px', height = '600px')
)
)
)
)
Server:
server <- function(input, output, session) {
output$coolplot <- renderPlotly({
ngo <-
ngo %>%
filter(Victim.Nationality %in% input$Nationality,
Victim.Gender %in% input$gender,
Trafficking.Type %in% input$traffickingType,
Trafficking.Sub.Type %in% input$traffickingSubType,
Data.Provided.By %in% input$Source
) %>%
plot_ly(labels = ~Trafficking.Type, type = "pie")
})
}
I want to be able to allow the user to select one input and it will update graph and the more they add the graph will keep updating.

Not the neatest but what about separating the filtering as below:
server <- function(input, output, session) {
output$coolplot <- renderPlotly({
req(c(input$gender, input$traffickingType, input$traffickingSubType))
if(!is.null(input$Nationality)) {
ngo <- ngo %>% filter(Victim.Nationality %in% input$Nationality)
}
if(!is.null(input$gender)) {
ngo <- ngo %>% filter(Victim.Gender %in% input$gender)
}
if(!is.null(input$traffickingType)) {
ngo <- ngo %>% filter(Trafficking.Type %in% input$traffickingType)
}
if(!is.null(input$traffickingSubType)) {
ngo <- ngo %>% filter(Trafficking.Sub.Type %in% input$traffickingSubType)
}
if(!is.null(input$Source)) {
ngo <- ngo %>% filter(Data.Provided.By %in% input$Source)
}
plot_ly(ngo, labels = ~Trafficking.Type, type = "pie")
})
}
shinyApp(ui, server)
Update
based on comment below.
I added req(c(input$gender, input$traffickingType, input$traffickingSubType)).
I left out input$Nationality as that equals "A" on startup and input$Source I assumed but you can add input$source to the vector c(...) above if you want.

Related

Save results from dynamically filtered data to a csv file

I'm trying to save the result of dynamically filtered data into a csv file ; I created a button etc but the app freezes up when i press it... any help would be much appreciated i'm new to Shiny unfortunately
library(dplyr)
library(shinyWidgets)
fpath <- '/dbfs/May2022'
# Define UI
ui <- fluidPage(theme = shinytheme("spacelab"),
navbarPage(
"Display Data",
tabPanel(
"Select File",
sidebarPanel(
selectInput('selectfile','Select File',choice = list.files(fpath, pattern = ".csv")),
mainPanel("Main Panel",dataTableOutput("ftxtout"),style = "font-size:50%") # mainPanel
), #sidebarPanel
), #tabPanel
tabPanel("Subset Data",
sidebarPanel(
dropdown(
label = "Please Select Columns to Display",
icon = icon("sliders"),
status = "primary",
pickerInput(
inputId = "columns",
# label = "Select Columns",
choices = NULL,
multiple = TRUE
)#pickerInput
), #dropdown
selectInput("v_attribute1", "First Attribute to Filter Data", choices = NULL),
selectInput("v_attribute2", "Second Attribute to Filter Data", choices = NULL),
selectInput("v_filter1", "First Filter", choices = NULL),
selectInput("v_filter2", "Second Filter", choices = NULL),
textInput("save_file", "Save to file:", value=""),
actionButton("doSave", "Save Selected Data")
), #sidebarPanel
mainPanel(tags$br(),tags$br(),
h4("Data Selection"),
dataTableOutput("txtout"),style = "font-size:70%"
) # mainPanel
), # Navbar 1, tabPanel
tabPanel("Create Label", "This panel is intentionally left blank")
) # navbarPage
) # fluidPage
# Define server function
server <- function(input, output, session) {
output$fileselected<-renderText({
paste0('You have selected: ', input$selectfile)
})
info <- eventReactive(input$selectfile, {
fullpath <- file.path(fpath,input$selectfile)
read.csv(fullpath, header = TRUE, sep = ",")
})
observeEvent(info(), {
df <- info()
vars <- names(df)
# Update select input immediately after clicking on the action button.
updatePickerInput(session, "columns","Select Columns", choices = vars, selected=vars[1:2])
})
observeEvent(input$columns, {
vars <- input$columns
updateSelectInput(session, "v_attribute1","First Attribute to Filter Data", choices = vars)
updateSelectInput(session, "v_attribute2","Second Attribute to Filter Data", choices = vars, selected=vars[2])
})
observeEvent(input$v_attribute1, {
choicesvar1=unique(info()[[input$v_attribute1]])
req(choicesvar1)
updateSelectInput(session, "v_filter1","First Filter", choices = choicesvar1)
})
observeEvent(input$v_attribute2, {
choicesvar2=unique(info()[[input$v_attribute2]])
req(choicesvar2)
updateSelectInput(session, "v_filter2","Second Filter", choices = choicesvar2)
})
output$ftxtout <- renderDataTable({
head(info())
}, options =list(pageLength = 5))
output$txtout <- renderDataTable({
f <- info() %>% subset(select = input$columns)
f$var1 <- f[[input$v_attribute1]]
f$var2 <- f[[input$v_attribute2]]
ff <- f %>% dplyr::filter(var1 == input$v_filter1 & var2 == input$v_filter2)
fff <- ff %>% subset(select=-c(var1,var2))
head(fff)
}, options =list(pageLength = 5)
) #renderDataTable
#Saving data
observeEvent(input$doSave, {
req(input$columns,input$v_attribute1,input$v_attribute2,input$v_filter1,input$v_filter2)
f <- info() %>% subset(select = input$columns)
f$var1 <- f[[input$v_attribute1]]
f$var2 <- f[[input$v_attribute2]]
ff <- f %>% dplyr::filter(var1 == input$v_filter1 & var2 == input$v_filter2)
fff <- ff %>% subset(select=-c(var1,var2))
fullfpath <- paste0(file.path(fpath,input$save_file),".csv",sep="")
write.csv(fff,fullfpath, row.names = True)
Save_done <- showNotification(paste("Data Has been saved"), duration = NULL)
})
} # server
# Create Shiny object
shinyApp(ui = ui, server = server)
I've tried a few different things but can't get it work, i'm not sure what i'm doing wrong here!
You have a typo when calling write.csv. The argument row.names should be TRUE and not True.
I also took the time to write the last observeEvent used to save the data to avoid creating two columns just for doing the subsetting.
observeEvent(input$doSave, {
req(
input$columns, input$v_attribute1,
input$v_attribute2, input$v_filter1,
input$v_filter2, input$save_file
)
df <- info() %>% select(all_of(input$columns))
df_filtered <- df %>%
dplyr::filter(
.data[[input$v_attribute1]] == input$v_filter1 &
.data[[input$v_attribute2]] == input$v_filter2
)
fullfpath <- paste0(file.path(fpath, input$save_file), ".csv", sep = "")
write.csv(df_filtered, fullfpath, row.names = TRUE)
Save_done <- showNotification(paste("Data Has been saved"), duration = NULL)
})
Full app:
library(dplyr)
library(shinyWidgets)
library(shinythemes)
fpath <- "sample_datasets"
# Define UI
ui <- fluidPage(
theme = shinytheme("spacelab"),
navbarPage(
"Display Data",
tabPanel(
"Select File",
sidebarPanel(
selectInput("selectfile", "Select File", choice = list.files(fpath, pattern = ".csv")),
mainPanel("Main Panel", dataTableOutput("ftxtout"), style = "font-size:50%") # mainPanel
), # sidebarPanel
), # tabPanel
tabPanel(
"Subset Data",
sidebarPanel(
dropdown(
size = "xs",
label = "Please Select Columns to Display",
icon = icon("sliders"),
status = "primary",
pickerInput(
inputId = "columns",
# label = "Select Columns",
choices = NULL,
multiple = TRUE
) # pickerInput
), # dropdown
selectInput("v_attribute1", "First Attribute to Filter Data", choices = NULL),
selectInput("v_attribute2", "Second Attribute to Filter Data", choices = NULL),
selectInput("v_filter1", "First Filter", choices = NULL),
selectInput("v_filter2", "Second Filter", choices = NULL),
textInput("save_file", "Save to file:", value = ""),
actionButton("doSave", "Save Selected Data")
), # sidebarPanel
mainPanel(
tags$br(),
tags$br(),
h4("Data Selection"),
dataTableOutput("txtout"),
style = "font-size:70%"
) # mainPanel
), # Navbar 1, tabPanel
tabPanel("Create Label", "This panel is intentionally left blank")
) # navbarPage
) # fluidPage
# Define server function
server <- function(input, output, session) {
output$fileselected <- renderText({
paste0("You have selected: ", input$selectfile)
})
info <- eventReactive(input$selectfile, {
fullpath <- file.path(fpath, input$selectfile)
read.csv(fullpath, header = TRUE, sep = ",")
})
observeEvent(info(), {
df <- info()
vars <- names(df)
# Update select input immediately after clicking on the action button.
updatePickerInput(session, "columns", "Select Columns", choices = vars, selected = vars[1:2])
})
observeEvent(input$columns, {
vars <- input$columns
updateSelectInput(session, "v_attribute1", "First Attribute to Filter Data", choices = vars)
updateSelectInput(session, "v_attribute2", "Second Attribute to Filter Data", choices = vars, selected = vars[2])
})
observeEvent(input$v_attribute1, {
choicesvar1 <- unique(info()[[input$v_attribute1]])
req(choicesvar1)
updateSelectInput(session, "v_filter1", "First Filter", choices = choicesvar1)
})
observeEvent(input$v_attribute2, {
choicesvar2 <- unique(info()[[input$v_attribute2]])
req(choicesvar2)
updateSelectInput(session, "v_filter2", "Second Filter", choices = choicesvar2)
})
output$ftxtout <- renderDataTable(
{
head(info())
},
options = list(pageLength = 5)
)
output$txtout <- renderDataTable(
{
f <- info() %>% subset(select = input$columns)
f$var1 <- f[[input$v_attribute1]]
f$var2 <- f[[input$v_attribute2]]
ff <- f %>% dplyr::filter(var1 == input$v_filter1 & var2 == input$v_filter2)
fff <- ff %>% subset(select = -c(var1, var2))
head(fff)
},
options = list(pageLength = 5)
) # renderDataTable
# Saving data
observeEvent(input$doSave, {
req(
input$columns, input$v_attribute1,
input$v_attribute2, input$v_filter1,
input$v_filter2, input$save_file
)
df <- info() %>% select(all_of(input$columns))
df_filtered <- df %>%
dplyr::filter(
.data[[input$v_attribute1]] == input$v_filter1 &
.data[[input$v_attribute2]] == input$v_filter2
)
fullfpath <- paste0(file.path(fpath, input$save_file), ".csv", sep = "")
write.csv(df_filtered, fullfpath, row.names = TRUE)
showNotification(paste("Data Has been saved"), duration = NULL)
})
} # server
# Create Shiny object
shinyApp(ui = ui, server = server)

How to visualise regression's predictions based on selected dataset and variables thereof

I have the following code that basically uploads the data and once you have clicked on the row of the dataset you have uploaded, it reads the file. If you go to the second page in the navbar called regression you can choose variables from the dataset and run linear model. That works with the summary table. I want to achieve is something like here: https://towardsdatascience.com/build-an-interactive-machine-learning-model-with-shiny-and-flexdashboard-6d76f59a37f9
I want the prediction table and plot visualisation based on what has been selected. Appreciate your understanding and helpfulness.
library(shiny)
library(magrittr)
library(shiny)
library(readxl)
library(tidyverse)
library(DT)
library(reactable)
ui <- navbarPage("Demo",
tabPanel("Data Manipulation",
sidebarLayout(
sidebarPanel(
fileInput("upload", "Upload your file", multiple = TRUE, accept = c(".csv", ".xlsx") ),
selectInput('mydropdown', label = 'Select', choices = 'No choices here yet'),
h2("Modify variable type"),
selectInput("var_name", "Select variable", choices = c()),
radioButtons("action", NULL,
choiceNames = c("Make factor", "Make numeric"),
choiceValues = c("factor", "numeric")),
actionButton("modify", "Do it!"),
verbatimTextOutput("str")
),
mainPanel(
DT::DTOutput("files"),
reactable::reactableOutput("uploaded_files")
)
)
),
tabPanel("Regression",
sidebarLayout(
sidebarPanel(
selectInput("dep_var", "Select dependent variable", choices = c()),
selectInput("ind_var", "Select independent variables", choices = c(), multiple = TRUE),
actionButton("submit_reg", "Do it!")),
mainPanel(
verbatimTextOutput(outputId = "regsum")
)
)
),
)
server <- function(input, output, session) {
output$files <- DT::renderDT({
DT::datatable(input$upload, selection = c("single"))
})
selected_file <- reactiveVal()
observe({
## when developing, use a sample file you have on your computer so that you
## can load it immediately instead of going through button clicks
# demofile <- "/path/to/your/file.csv"
# selected_file( read.csv(demofile) )
# return()
req(input$upload, input$files_rows_selected)
idx <- input$files_rows_selected
file_info <- input$upload[idx, ]
if (tools::file_ext(file_info$datapath) == "csv") {
selected_file(read.csv(file_info$datapath))
} else if (tools::file_ext(file_info$datapath) == "xlsx") {
selected_file(readxl::read_xlsx(file_info$datapath))
} else {
stop("Invalid file type")
}
})
output$uploaded_files <- reactable::renderReactable({
req(selected_file())
reactable::reactable(
selected_file(),
searchable = TRUE
)
})
observe({
req(input$upload)
file_names <- input$upload$name
updateSelectInput(
session,
"mydropdown",
choices = file_names
)
})
observe({
req(selected_file())
updateSelectInput(session, "var_name", choices = names(selected_file()))
})
output$str <- renderPrint({
req(selected_file())
str(selected_file())
})
observeEvent(input$modify, {
df <- selected_file()
if (input$action == "factor") {
df[[input$var_name]] <- as.factor(df[[input$var_name]])
} else if (input$action == "numeric") {
df[[input$var_name]] <- as.numeric(df[[input$var_name]])
} else {
stop("Invalid action")
}
selected_file(df)
})
# Second Page
observe({
req(selected_file())
Dependent <- updateSelectInput(session, "dep_var", choices = names(selected_file()))
})
observe({
req(selected_file())
Independent <- updateSelectInput(session, "ind_var", choices = names(selected_file()))
})
observeEvent(input$submit_reg, {
lm1 <- reactive({
req(selected_file())
Model1 <- lm(reformulate(input$ind_var, input$dep_var), data = selected_file())})
options(scipen=999)
output$regsum <- renderPrint({summary(lm1())})
DT::renderDataTable({
df <- req(selected_file())
DT::datatable(df %>% select(input$dep_var, input$ind_var) %>% mutate(predicted = predict(lm1()), residuals = residuals(lm1())) %>% select(input$dep_var, predicted, residuals),
rownames = FALSE, colnames = c('actual value', 'predicted value', 'residuals'), extensions = c('Buttons', 'Responsive'),
options = list(columnDefs = list(list(className = 'dt-center', targets = "_all")), dom = 'Blfrt',
buttons = c('copy', 'csv', 'excel', 'print'), searching = FALSE, lengthMenu = c(20, 100, 1000, nrow(housing)), scrollY = 300, scrollCollapse = TRUE))
})
})
}
shinyApp(ui, server)

Reactive Dataset on Download Handler

I have a shiny app linked to a duckdb. Since I have a very big dataset I just want to load in 10'000 rows. However as soon as the user downloads the dataset it should download the entire dataset and not just the first 10'000 rows. So I guess there should be some kind of if condition where i specify the "LIMIT 10000" which reacts on the download handler. However, I dont know how to change the LIMIT based on the download handler.
BestandeslisteDaten_UI <- function(id3, mydb, data_Vertrag){
ns <- NS(id3)
tagList(
fluidRow(
box(
title = "Daten Bestandesliste", status = "primary", solidHeader = TRUE,
collapsible = TRUE, width=9,
DTOutput(ns("dt31"))
),
box(
title = "Einschränkung des Datenset", status = "primary", solidHeader = TRUE,
collapsible = TRUE, width=3, height = "110em",
downloadButton(ns("download32"),"Download entire Table as csv")
)
)
)
}
BestandeslisteDaten_Server <- function(id3, mydb, data_Vertrag){
moduleServer(
id3,
function(input, output, session){
filter_BestandVertrag_Daten <- reactive({
query <- glue_sql("SELECT * FROM data_Vertrag",
.con = mydb)
add_where <- TRUE
query <- glue_sql(query, " LIMIT 10000", .con = mydb)
print(query)
dt <- as.data.table(dbGetQuery(mydb, query))
print(dt)
dt
})
# Data Table
output$dt31 <- renderDT({
filter_BestandVertrag_Daten() %>%
datatable(
extensions = 'Buttons',
options = list(
server = TRUE,
lengthMenu=c(10, 100),
scrollX = TRUE,
scrollY = "500px",
dom = 'Blfrtip'
))
})
# Download Datatable
output$download32 <- downloadHandler(
filename = function() {
paste("Bestandesliste_", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(filter_BestandVertrag_Daten(), file)
}
)
}
)
}

How do I resolve error message stating "Error in $<-,data.frame: replacement has 0 rows, data has 1352"?

I am hoping for some help. I am the newest of the newbees and attempting to make this code work utilizing ShinyApp. Upon running my codes, I am receiving the error message of:
Warning: Error in $<-.data.frame: replacement has 0 rows, data has 1352
Is there anything that appears incorrect with my code that stands out? or any suggestions on next tries?
ui.R Code
library(shiny)
library(plotly)
library(DT)
mobility <- read.csv("mobility_data.csv", sep = ',')
mobility$Date <- as.Date(mobility$Date, format="%m/%d/%Y")
mobility$Province <- as.factor(mobility$Province)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
h2("COVID-19 Mobility Data"),
selectInput(inputId = "dv", label = "Category",
choices = c("Retail_Recreation", "Grocery_Pharmarcy", "Parks", "Transit_Stations", "Workplaces", "Residential"),
selected = "Grocery_Pharmarcy"),
selectInput(inputId = "provinces", "Province(s)",
choices = levels(mobility$Province),
multiple = TRUE,
selected = c("Utrecht", "Friesland", "Zeeland")),
dateRangeInput(inputId = "date", label = "Date range",
start = min(mobility$Date),
end = max(mobility$Date)),
downloadButton(outputId = "download_data", label = "Download"),
),
mainPanel(
plotlyOutput(outputId = "plot"),
em("Postive and negative percentages indicate an increase and decrease from the baseline period (median value between January 3 and February 6, 2020) respectively."),
DT::dataTableOutput(outputId = "table")
)
)
)
server.R code
server <- function(input, output) {
filtered_data <- reactive({
subset(mobility,
Province %in% input$provinces &
Date >= input$date[1] & Date <= input$date[2])})
output$plot <- renderPlotly({
ggplotly({
p <- ggplot(filtered_data(), aes_string(x = "Date", y = input$dv, color = "Province")) +
geom_point(alpha = 0.5) + theme(legend.position = "none") + ylab("% change from baseline")
p
})
})
output$table <- DT::renderDataTable({
filtered_data()
})
output$download_data <- downloadHandler(
filename = "Mobility_Data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
}
Here is the first seven rows from of sample data from my dataset entitled "mobility_data" as well:
structure(list(Country = c("Netherlands", "Netherlands", "Netherlands",
"Netherlands", "Netherlands", "Netherlands", "Netherlands"),
Province = c("Flevoland", "Flevoland", "Flevoland", "Flevoland",
"Flevoland", "Flevoland", "Flevoland"), Date = c("2/15/2020",
"2/16/2020", "2/17/2020", "2/18/2020", "2/19/2020", "2/20/2020",
"2/21/2020"), Retail_Recreation = c(-2L, -17L, 0L, 6L, 2L,
-2L, 4L), Grocery_Pharmarcy = c(-3L, -13L, -6L, -2L, -7L,
-5L, -1L), Parks = c(4L, -30L, 3L, 30L, 27L, 3L, 21L), Transit_Stations = c(5L,
-9L, -14L, -13L, -15L, -16L, -11L), Workplaces = c(-1L, -7L,
-19L, -18L, -18L, -20L, -21L), Residential = c(0L, 1L, 3L,
3L, 2L, 3L, 2L)), row.names = c(NA, 7L), class = "data.frame")
You can read the csv file using fileInput. Try this
library(shiny)
library(plotly)
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
h2("COVID-19 Mobility Data"),
fileInput("file1", "Choose CSV file to upload", accept = ".csv"),
selectInput(inputId = "dv", label = "Category",
choices = c("Retail_Recreation", "Grocery_Pharmarcy", "Parks", "Transit_Stations", "Workplaces", "Residential"),
selected = "Grocery_Pharmarcy"),
selectInput(inputId = "provinces", "Province(s)",
choices = levels(mobility$Province),
multiple = TRUE,
selected = c("Utrecht", "Friesland", "Zeeland")),
dateRangeInput(inputId = "date", label = "Date range",
start = min(mobility$Date),
end = max(mobility$Date)),
downloadButton(outputId = "download_data", label = "Download"),
),
mainPanel(
plotlyOutput(outputId = "plot"),
em("Postive and negative percentages indicate an increase and decrease from the baseline period (median value between January 3 and February 6, 2020) respectively."),
DT::dataTableOutput(outputId = "table")
)
)
)
server <- function(input, output) {
mobility <- reactive({
infile <- input$file1
req(infile)
return(read.csv(infile$datapath, header=TRUE, sep=','))
})
filtered_data <- reactive({
subset(mobility(),
Province %in% input$provinces &
Date >= input$date[1] & Date <= input$date[2])})
output$plot <- renderPlotly({
ggplotly({
p <- ggplot(filtered_data(), aes_string(x = "Date", y = input$dv, color = "Province")) +
geom_point(alpha = 0.5) + theme(legend.position = "none") + ylab("% change from baseline")
p
})
})
output$table <- DT::renderDataTable({
filtered_data()
})
output$download_data <- downloadHandler(
filename = "Mobility_Data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
}
shinyApp(ui, server)

Have multiple inputs going into multiple graphs but only 3 out of the 5 are working

I have created multiple selectInputs that will alter multiple graphs when something from the drop down menu has been selected. Currently only 3 out of the 5 graphs are working even though they all have the same code. So far the trafficking type, sub type and gender work but the control method and transportation method are not.
UI:
ui <- dashboardPage(
dashboardHeader(title = "Human Trafficking"),
dashboardSidebar(
sidebarMenu(
selectInput("Source", "Choose a Data Source: ", choices = sort(unique(newNgo$Data.Source)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
selectInput("Nationality", "Select a nation: ", choices = " "),
dateInput("startdate", "Start Date:", value = "2019-08-01", format = "dd-mm-yyyy",
min = "2000-01-01", max = "2019-09-04"),
dateInput("enddate", "End Date:", value = "2019-09-05", format = "dd-mm-yyyy",
min = "2000-01-02", max = "2019-09-05")
#actionButton("button1", "Apply"),
#actionButton("reset_input", "Reset inputs")
)
),
fluidRow(
box(width = 6, solidHeader = TRUE, status = "primary",
title = "Trafficking Type",
selectInput("traffickingType", "Choose a trafficking type: ",
choices = sort(unique(newNgo$Trafficking.Type)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
#actionButton("button2", "Apply"),
plotlyOutput("coolplot", width = '750px', height = '300px')
),
box(width = 6, solidHeader = TRUE, status = "primary",
title = "Trafficking Sub-Type",
selectInput("traffickingSubType", "Choose a trafficking sub type: ",
choices = sort(unique(newNgo$Trafficking.Sub.Type)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
#actionButton("button3", "Apply"),
plotlyOutput("Sub", width = '750px', height = '300px')
)
),
fluidRow(
box(width = 4, solidHeader = TRUE, status = "primary",
title = "Victim Gender",
selectInput("victimGender", "Choose a gender: ",
choices = sort(unique(newNgo$Victim.Gender)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
#actionButton("button4", "Apply"),
plotlyOutput("gender", width = '250px', height = '200px')
),
box(width = 4, solidHeader = TRUE, status = "primary",
title = "Transport Method",
selectInput("transp", "Choose a transportation method: ",
choices = sort(unique(newNgo$Transportation.Method)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
#actionButton("button4", "Apply"),
plotlyOutput("transportMethod", width = '250px', height = '200px')
),
box(width = 4, solidHeader = TRUE, status = "primary",
title = "Control Method",
selectInput("control", "Choose a control method: ",
choices = sort(unique(newNgo$Control.Method)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
#actionButton("button4", "Apply"),
plotlyOutput("controlMethod", width = '250px', height = '200px')
)
Server:
output$coolplot <- renderPlotly({
req(input$Nationality)
if(!is.null(input$Nationality)) {
newNgo <- newNgo %>% filter(Victim.Nationality %in% input$Nationality)
}
if(!is.null(input$gender)) {
newNgo <- newNgo %>% filter(Victim.Gender %in% input$gender)
}
if(!is.null(input$traffickingType)) {
newNgo <- newNgo %>% filter(Trafficking.Type %in% input$traffickingType)
}
if(!is.null(input$traffickingSubType)) {
newNgo <- newNgo %>% filter(Trafficking.Sub.Type %in% input$traffickingSubType)
}
if(!is.null(input$Source)) {
newNgo <- newNgo %>% filter(Data.Source %in% input$Source)
}
plot_ly(newNgo, labels = ~Trafficking.Type, type = "pie") %>%
layout(showlegend = FALSE)
})
output$control <- renderPlotly({
req(input$Nationality)
if(!is.null(input$Nationality)) {
newNgo <- newNgo %>% filter(Victim.Nationality %in% input$Nationality)
}
if(!is.null(input$gender)) {
newNgo <- newNgo %>% filter(Victim.Gender %in% input$gender)
}
if(!is.null(input$traffickingType)) {
newNgo <- newNgo %>% filter(Trafficking.Type %in% input$traffickingType)
}
if(!is.null(input$traffickingSubType)) {
newNgo <- newNgo %>% filter(Trafficking.Sub.Type %in% input$traffickingSubType)
}
if(!is.null(input$Source)) {
newNgo <- newNgo %>% filter(Data.Source %in% input$Source)
}
plot_ly(newNgo, labels = ~Control.Method, type = "pie") %>%
layout(showlegend = FALSE)
})
I have attached the code from the server with one graph that works and one that doesn't work. I also attached all the different inputs I have from the UI.
Your plotlyOutput in the ui has the id controlMethod, whereas your output id in the server is control. Change the latter to output$controlMethod.