cleaning up my understanding of Shiny modules - r

I have a project and I would like to start modularising my code in my Shiny App. I would like to get my head around a few things regarding modules.
I can pass the UI modules to the user interface without any issue ui_MODULE and ui_MODULE_LOCATIONS. My problem arises when I try to pass the server module to the App server_location_dropdown_filter. How can I fix this issue?
My modules are called ui_MODULE("myMODUEL") and ui_MODULE_LOCATIONS("myMODULE2") - I know the myMODULE and myMODULE2 are passed to the NS but I am still having a little difficulty understanding how this part works intuitively - I thought we could reuse the modules by calling them again but this time passing a new NS to the module - i.e. in the App I pass ui_MODULE_LOCATIONS("USE_AGAIN") - but I do not get the location dropdowns again... How can I correctly re-use the modules?
I would like to understand a bit better how I can correctly modularise my projects. I read a lot about modules online but I find it easier to learn by applying it to my own code. Can you help modularise the following App?
Shiny App:
library(bslib)
library(shiny)
library(dplyr)
library(tidyr)
library(reactable)
################ GENERATE DATA ##############################
# Define the US states and cities
us_states <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California")
alabama_cities <- c("Birmingham", "Huntsville", "Mobile", "Montgomery", "Tuscaloosa")
alaska_cities <- c("Anchorage", "Fairbanks", "Juneau", "Sitka", "Wasilla")
arizona_cities <- c("Phoenix", "Tucson", "Mesa", "Chandler", "Scottsdale")
arkansas_cities <- c("Little Rock", "Fort Smith", "Fayetteville", "Springdale", "Jonesboro")
california_cities <- c("Los Angeles", "San Francisco", "San Diego", "San Jose", "Fresno")
# Set the seed for reproducibility
set.seed(123)
# Generate random price and quantity data
data <- tibble(
state = sample(us_states, 5000, replace = TRUE),
city = case_when(
state == "Alabama" ~ sample(alabama_cities, 5000, replace = TRUE),
state == "Alaska" ~ sample(alaska_cities, 5000, replace = TRUE),
state == "Arizona" ~ sample(arizona_cities, 5000, replace = TRUE),
state == "Arkansas" ~ sample(arkansas_cities, 5000, replace = TRUE),
state == "California" ~ sample(california_cities, 5000, replace = TRUE)
),
price = runif(5000, 10, 100),
quantity = sample(1:10, 5000, replace = TRUE)
)
#############################################################
################# UI ###################
ui_MODULE <- function(id) {
ns <- NS(id)
tagList(
tags$div(
class = "panel-header",
numericInput("price", label = "Price?", value = 10, min = 1, step = 500),
numericInput("quantity", label = "Quantity?", value = 10000, min = 1, step = 50),
sliderInput("discount", label = "Discount", min = 0, max = 0.25, post = " %", value = 0.08, step = 0.001),
actionButton("compute", "Compute!")
)
)
}
################# UI LOCATIONS ###############
ui_MODULE_LOCATIONS = function(id){
ns <- NS(id)
tagList(
tags$div(
class = "panel-header-locations",
selectInput("stateSelect", label = "Select State Data", choices = c()),
selectInput("citySelect", label = "Select City Variable", choices = c()),
)
)
}
################## SERVER MODUEL ############
# This doesn't work correctly...
server_location_dropdown_filter <- function(id){
moduleServer(id, function(input, output, session){
# Changes with changes in the slider input
updatedTable = reactive(
data %>%
filter(state == input$stateSelect) %>%
filter(city == input$citySelect)
)
output$table = DT::renderDT({
updatedTable()
})
})
}
############### FUNCTIONS ###################
myFUNCTION = function(interest){
data %>%
mutate(
p_q = price * quantity,
someOtherCalc = p_q*interest
)
}
# myFUNCTION(0.08)
#############################################
ui <- bootstrapPage(
theme = bs_theme(version = 5, bootswatch = 'minty'),
#titlePanel("Old Faithful Geyser Data"),
navbarPage("App Title",
tabPanel("Plot",
fluidPage(
fluidRow(
column(6,
##### UI #######
ui_MODULE("myMODUEL")
),
column(6,
#### UI Locations ####
ui_MODULE_LOCATIONS("myMODULE2")
)
),
fluidRow(
column(6,
DT::DTOutput('table')
),
column(6,
DT::DTOutput('newTableOUT')
)
)
)
),
tabPanel("use_UI_Again",
fluidPage(
fluidRow(
column(12,
ui_MODULE_LOCATIONS("USE_AGAIN")
)
)
)
)
)
)
server <- function(input, output, session) {
# (1) First observe the states unique values in the data
observe({
choices = data %>% select(state) %>% unique() %>% pull(state)
updateSelectInput(
session,
"stateSelect",
choices = choices
)
})
## (2) ## The cities are then updated to reflect the states selection
observeEvent(input$stateSelect,{
choices = data %>% filter(state == input$stateSelect) %>% select(city) %>% unique() %>% pull(city)
updateSelectInput(
session,
"citySelect",
choices = choices
)
})
#server_location_dropdown_filter("myFILTERS") # here I can't get this working...so I have to run the updatedTable and output$table here
updatedTable = reactive(
data %>%
filter(state == input$stateSelect) %>%
filter(city == input$citySelect)
)
output$table = DT::renderDT({
updatedTable()
})
# Now I want to update the table by using a function...
newTable = reactive(
updatedTable() %>%
myFUNCTION(input$discount)
)
output$newTableOUT = DT::renderDT({
newTable()
})
}
shinyApp(ui = ui, server = server)

You have a few issues. First, you need to use namespace (ns) for each inputID in the module UIs. Second, you need to define a server module to return the input variables from ui_MODULE. Lastly, if you wish to call a ui module again, you need to call the corresponding server module again.
Try this
library(bslib)
library(shiny)
library(dplyr)
library(tidyr)
library(reactable)
library(DT)
################ GENERATE DATA ##############################
# Define the US states and cities
us_states <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California")
alabama_cities <- c("Birmingham", "Huntsville", "Mobile", "Montgomery", "Tuscaloosa")
alaska_cities <- c("Anchorage", "Fairbanks", "Juneau", "Sitka", "Wasilla")
arizona_cities <- c("Phoenix", "Tucson", "Mesa", "Chandler", "Scottsdale")
arkansas_cities <- c("Little Rock", "Fort Smith", "Fayetteville", "Springdale", "Jonesboro")
california_cities <- c("Los Angeles", "San Francisco", "San Diego", "San Jose", "Fresno")
# Set the seed for reproducibility
set.seed(123)
# Generate random price and quantity data
data <- tibble(
state = sample(us_states, 5000, replace = TRUE),
city = case_when(
state == "Alabama" ~ sample(alabama_cities, 5000, replace = TRUE),
state == "Alaska" ~ sample(alaska_cities, 5000, replace = TRUE),
state == "Arizona" ~ sample(arizona_cities, 5000, replace = TRUE),
state == "Arkansas" ~ sample(arkansas_cities, 5000, replace = TRUE),
state == "California" ~ sample(california_cities, 5000, replace = TRUE)
),
price = runif(5000, 10, 100),
quantity = sample(1:10, 5000, replace = TRUE)
)
#############################################################
################# UI ###################
ui_MODULE <- function(id) {
ns <- NS(id)
tagList(
tags$div(
class = "panel-header",
numericInput(ns("price"), label = "Price?", value = 10, min = 1, step = 500),
numericInput(ns("quantity"), label = "Quantity?", value = 10000, min = 1, step = 50),
sliderInput(ns("discount"), label = "Discount", min = 0, max = 0.25, post = " %", value = 0.08, step = 0.001),
actionButton(ns("compute"), "Compute!")
)
)
}
server_module <- function(id){
moduleServer(id, function(input, output, session){
rv <- reactiveValues()
observe({
rv$price <- input$price
rv$discount <- input$discount
})
return(rv)
})
}
################# UI LOCATIONS ###############
ui_MODULE_LOCATIONS = function(id){
ns <- NS(id)
tagList(
tags$div(
class = "panel-header-locations",
selectInput(ns("stateSelect"), label = "Select State Data", choices = c()),
selectInput(ns("citySelect"), label = "Select City Variable", choices = c()),
)
)
}
################## SERVER MODUEL ############
# This doesn't work correctly...
server_location_dropdown_filter <- function(id){
moduleServer(id, function(input, output, session){
# Changes with changes in the slider input
# (1) First observe the states unique values in the data
observe({
choices = data %>% select(state) %>% unique() %>% pull(state)
updateSelectInput(
session,
"stateSelect",
choices = choices
)
})
## (2) ## The cities are then updated to reflect the states selection
observeEvent(input$stateSelect,{
choices = data %>% filter(state == input$stateSelect) %>% select(city) %>% unique() %>% pull(city)
updateSelectInput(
session,
"citySelect",
choices = choices
)
})
updatedTable = reactive(
data %>%
filter(state == input$stateSelect) %>%
filter(city == input$citySelect)
)
return(updatedTable)
})
}
############### FUNCTIONS ###################
myFUNCTION <- function(data,interest){
df <- data %>%
dplyr::mutate(p_q = price * quantity) %>%
dplyr::mutate(
someOtherCalc = p_q * interest
)
return(df)
}
# myFUNCTION(0.08)
#############################################
ui <- bootstrapPage(
theme = bs_theme(version = 5, bootswatch = 'minty'),
#titlePanel("Old Faithful Geyser Data"),
navbarPage("App Title",
tabPanel("Plot",
fluidPage(
fluidRow(
column(6,
##### UI #######
ui_MODULE("myMODULE")
),
column(6,
#### UI Locations ####
ui_MODULE_LOCATIONS("myMODULE2")
)
),
fluidRow(
column(6,
DT::DTOutput('table')
),
column(6,
DT::DTOutput('newTableOUT')
)
)
)
),
tabPanel("use_UI_Again",
fluidPage(
fluidRow(
column(6,
ui_MODULE("USE_AGAIN")
),
column(6,
ui_MODULE_LOCATIONS("USE_AGAIN2")
)
),
fluidRow(
column(6,
DT::DTOutput('table2')
),
column(6,
DT::DTOutput('newTableOUT2')
)
)
)
)
)
)
server <- function(input, output, session) {
updatedTable <- server_location_dropdown_filter("myMODULE2")
output$table = DT::renderDT({
updatedTable()
})
values <- server_module("myMODULE")
newTable = reactive({
req(updatedTable(),values$discount)
myFUNCTION(updatedTable(),values$discount)
})
output$newTableOUT = DT::renderDT({
newTable()
})
### USE MODULES again
updatedTable2 <- server_location_dropdown_filter("USE_AGAIN2")
output$table2 = DT::renderDT(updatedTable2())
values2 <- server_module("USE_AGAIN")
newTable2 = reactive({
req(updatedTable2(),values2$discount)
myFUNCTION(updatedTable2(),values2$discount)
})
output$newTableOUT2 = DT::renderDT(newTable2())
}
shinyApp(ui = ui, server = server)

Related

Warning: Error in [[<-.data.frame: replacement has 1 row, data has 0

My objective is to plot some graphs based on the data uploaded by users. Users can select how it is plotted. It works but there are warnings showing in the console. I think the issue lies with how the server module looks up values in the UI module but the UI module is not yet initalised. How can I get rid of the warnings? Thanks
Sample data:
fwrite(data.table(
age.band = c("45-54","55-64","55-64","55-64","55-64","45-54","35-44","25-34"),
gender = c("MALE","FEMALE","FEMALE","FEMALE","FEMALE","FEMALE","MALE","FEMALE"),
event = c("13/04/2022","8/04/2022","20/05/2021","12/02/2022","19/02/2021","19/03/2022","16/03/2021","19/03/2021"),
cause = c('Cancer','Cancer','Cancer','Mental Illness','Cancer','Musculoskeletal','Mental Illness','Musculoskeletal'),
type= c('Type1','Type1','Type1','Type2','Type2','Type2','Type2','Type2'),
rate = rep(1,8),
status = rep("accepted",8)
),"sample.csv",row.names=F)
Here is my code:
### UI and server to load data
loadDataUI <- function(id,label = "Upload",buttonLabel = "Browse") {
ns <- NS(id)
tagList(
fileInput(ns("file"),label=label,buttonLabel=buttonLabel,accept = c('.csv'),placeholder = "No file selected")
)
}
loadData <- function(id) {
moduleServer(
id,
function(input, output, session) {
userFile <- reactive({
shiny::validate(need(input$file, message = FALSE))
input$file
})
dt <- reactive({fread(userFile()$datapath)})
return(dt)
}
)
}
### UI and server to plot data
edaUI <- function(id,cat.option) {
ns <- NS(id)
tagList(
box(
dropdown(
selectInput(inputId = ns('category'),
label = 'Category',
choices = cat.option,selected = "all"),
dateRangeInput(ns("eventdaterange"), "Loss date range",
start = Sys.Date()-10,
end = Sys.Date()+10)
),
highchartOutput(ns("hc_init"))
)
)
}
eda <- function(id,filtered.data,measure){
moduleServer(
id,
function(input, output, session) {
observeEvent(filtered.data(), {
updateDateRangeInput(session,"eventdaterange",
start = min(filtered.data()$event),
end = max(filtered.data()$event))
})
output$hc_init <- renderHighchart({
tmp <- filtered.data() %>%
filter(event >= input$eventdaterange[1],event <= input$eventdaterange[2]) %>%
mutate(event.date = as.character(as.yearqtr(event)))
if (input$category == "all") {
tmp %>% group_by(event.date) %>%
summarise(measure=sum(!!sym(measure))) %>%
hchart("line", hcaes(x = event.date, y = measure)) %>%
hc_title(text="Chart")
} else {
tmp %>%
group_by(cat = !!sym(input$category),event.date) %>%
summarise(measure=sum(!!sym(measure))) %>% ungroup() %>%
arrange(cat,event.date) %>%
hchart("line", hcaes(x = event.date, y = measure,group = cat)) %>%
hc_title(text="Chart")
}
})
}
)
}
### Main UI and server
ui <- function() {
fluidPage(useShinydashboard(),
navbarPage(
tabPanel(
title = "Data analysis",
sidebarLayout(
sidebarPanel(
width = 2,
loadDataUI("input","","Upload data"),
awesomeRadio(
inputId = "benefit",
label = strong("Select type"),
choices = c("Type1", "Type2"),
selected = NULL,inline = TRUE,checkbox = FALSE)
),
mainPanel(
width = 10,edaUI("dt1",cat.option=c("all","age.band","gender"))
)
)
)
)
)
}
server <- function(input, output, session) {
data <- loadData("input")
filtered_data <- reactive({
date.cols <- c("event")
data()[type == input$benefit][,(date.cols):= lapply(.SD, dmy),.SDcols = date.cols]
})
eda("dt1",filtered_data,measure="rate")
}
shinyApp(ui = ui, server = server)

How to connect Action Button with Material Switch Shiny

I have a shiny module where I want to read one data frame or another based on the user's selection. After the user selects one data frame or another, I want to give the user the option to plot one variable or another using a material switch. Mexico button means that it will be a data frame grouped by states. Municipal button means that it is a data frame grouped by municipality.
I am struggling to connect the material switch with the df selected with the action button. I have just tried with one action button.
Here is the code
require(shiny)
require(ggplot2)
require(dplyr)
require(tidyr)
require(readr)
require(data.table)
require(shinyWidgets)
require(ggplot2)
mod_dfSelector_ui <- function(id){
ns <- NS(id)
fluidRow(
column(2,
actionButton(inputId = ns("mexico_df"),
label = "Mexico")),
column(2,
actionButton(inputId = ns("municipal_df"),
label = "Municipal")),
column(4,
tags$div(
materialSwitch(inputId = "cumdeath", label = "Cumulative sum of covid deaths",
inline = TRUE),
tags$div(
materialSwitch(inputId = "exdeath", label = "Excess mortality",
inline = TRUE)
)
)
),
column(2,
plotOutput(
outputId = ns("plot"))
)
)
}
mod_dfSelector_server <- function(id){
moduleServer(id, function(input, output, session){
ns <- session$ns
# ----- buttons
countryDF <- eventReactive(input$mexico_df,{
fread("../data-raw/mexico-covid-final.csv", header = T) %>%
group_by(id_ent, month_def, year_def) %>%
summarise(tot_covid_deaths = sum(tot_covid_deaths, na.rm = T),
excess_mortality_ssa = sum(excess_mortality_ssa, na.rm = T),
excess_mortality_inegi = sum(excess_mortality_inegi, na.rm = T))
})
municipalDF <- eventReactive(input$municipal_df,{
fread("../data-raw/mexico-covid-final.csv", header = T)
})
# ---- switch
cumulativeEnt <- eventReactive(input$cumdeath, {
countryDF() %>%
select(month_def, year_def, tot_covid_deaths)
})
output$plot <- renderPlot({
cumulativeEnt() %>%
ggplot(aes(tot_covid_deaths)) +
geom_histogram()
})
})
}
## To be copied in the UI
# mod_histogram_ui("histogram_ui_1")
## To be copied in the server
# mod_histogram_server("histogram_ui_1")
ui <- fluidPage(
mod_dfSelector_ui("country")
)
server <- function(input, output, session) {
mod_dfSelector_server("country")
}
shinyApp(ui, server)

Shiny output plot based on input inside bs_accordion

I have a set of inputs inside bs_accordion and would like to output a plot based on the selected inputs and active/expanded panel, but I'm not sure how to link the selected input based on this active/expanded panel. Is there a way to know which panel is active? My code is below and thank you in advance.
library(shiny)
library(bsplus)
library(shinyjs)
month_data <- data.frame(Region = c(rep("Region M1", 20), rep("Region M2", 20)),
Value = runif(40))
day_data <- data.frame(Region = c(rep("Region D3", 20), rep("Region D4", 20)),
Value = runif(40))
m1 <- selectInput(inputId = "in_month_region", label = "Region", choices = c("Region M1", "Region M2"))
d1 <- selectInput(inputId = "in_day_region", label = "Region", choices = c("Region D3", "Region D4"))
ui <- fluidPage(
useShinyjs(),
actionButton(inputId = "toggle_menu", label = "Options"),
br(),
sidebarLayout(
div(id = "Sidebar",
sidebarPanel(width = 3,
bs_accordion(id = "input_panel") %>%
bs_set_opts(panel_type = "success", use_heading_link = TRUE) %>%
bs_append(title = "Monthly",
content = m1) %>%
bs_append(title = "Daily",
content = d1))),
mainPanel(plotOutput("myplot"))
)
)
server <- function(input, output, session){
observeEvent(input$toggle_menu, {
shinyjs::toggle(id = "Sidebar")
})
get_data <- reactive({
if(!input$in_month_region %in% c(NULL, "")){
a <- subset(month_data, Region %in% input$in_month_region)
} else if(!input$in_day_region %in% c(NULL, "")){
a <- subset(day_dat, Region %in% input$in_day_region)
}
return(a)
})
output$myplot <- renderPlot({
mydat <- get_data()
plot(mydat$Value, main = unique(mydat$Region))
})
}
shinyApp(ui, server)

Shiny R: Modifying the variable class

I am trying to create a shiny-app that load data-set, present the variable list and their classes and allow the user to modify the class of a selected variable. All the functions in the following code are working except to the last function in the server- observeEvent which not working when trying to modify the variable class. Any suggestions?
Thank you in advance,
Rami
`
rm(list = ls())
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Shiny Example"),
#--------------------------------------------------------------------
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("th"))
)
),
#--------------------------------------------------------------------
dashboardBody(
#--------------------------------------------------------------------
tabItem(tabName = "data",
fluidPage(
fluidRow(
box(
selectInput('dataset', 'Select Dataset', list(GermanCredit = "GermanCredit",
cars = "cars",
iris = "iris")),
title = "Datasets",width = 4, status = "primary",
checkboxInput("select_all", "Select All Variable", value = TRUE),
conditionalPanel(condition = "input.select_all == false",
uiOutput("show.var"))
),
box(
title = "Variable Summary", width = 4, status = "primary",
DT::dataTableOutput('summary.data')
),
box(
title = "Modify the Variable Class", width = 4, status = "primary",
radioButtons("choose_class", label = "Modify the Variable Class",
choices = list(Numeric = "numeric", Factor = "factor",
Character = "character"),
selected = "numeric"),
actionButton("var_modify", "Modify")
)
)
)
)
)
)
#--------------------------------------------------------------------
# Server Function
#--------------------------------------------------------------------
server <- function(input, output,session) {
#--------------------------------------------------------------------
# loading the data
get.df <- reactive({
if(input$dataset == "GermanCredit"){
data("GermanCredit")
GermanCredit
}else if(input$dataset == "cars"){
data(cars)
cars
}else if(input$dataset == "iris"){
data("iris")
iris
}
})
# Getting the list of variable from the loaded dataset
var_list <- reactive(names(get.df()))
# Choosing the variable - checkbox option
output$show.var <- renderUI({
checkboxGroupInput('show_var', 'Select Variables', var_list(), selected = var_list())
})
# Setting the data frame based on the variable selction
df <- reactive({
if(input$select_all){
df <- get.df()
} else if(!input$select_all){
df <- get.df()[, input$show_var, drop = FALSE]
}
return(df)
})
# create list of variables
col.name <- reactive({
d <- data.frame(names(df()), sapply(df(),class))
names(d) <- c("Name", "Class")
return(d)
})
# render the variable list into table
output$summary.data <- DT::renderDataTable(col.name(), server = FALSE, rownames = FALSE,
selection = list(selected = 1, mode = 'single'),
options = list(lengthMenu = c(5, 10, 15, 20), pageLength = 20, dom = 'p'))
# storing the selected variable from the variables list table
table.sel <- reactive({
df()[,which(colnames(df()) == col.name()[input$summary.data_rows_selected,1])]
})
# Trying to modify the variable class
observeEvent(input$var_modify,{
modify.row <- which(colnames(df()) == col.name()[input$summary.data_rows_selected,1])
if( input$choose_class == "numeric"){
df()[, modify.row] <- as.numeric(df()[, modify.row])
} else if( input$choose_class == "factor"){
df()[, modify.row] <- as.factor(df()[, modify.row])
} else if( input$choose_class == "character"){
df()[, modify.row] <- as.character(df()[, modify.row])
}
})
}
shinyApp(ui = ui, server = server)
`
I would use reactiveValues() instead.
library(shiny)
# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("classType", "Class Type:", c("as.numeric", "as.character"))
),
mainPanel(
textOutput("class")
)
)
))
server <- shinyServer(function(input, output) {
global <- reactiveValues(sample = 1:9)
observe({
global$sample <- get(input$classType)(global$sample)
})
output$class <- renderText({
print(class(global$sample))
})
})
shinyApp(ui = ui, server = server)
In case you are interested:
Concerning your attempt: reactive() is a function and you called the output of the function by df()[, modify.row]. So in your code you try to change the output of the function, but that does not change the output of futures calls of that function.
Maybe it is easier to see in a simplified version:
mean(1:3) <- 1
The code can not change the mean function to output 1 in future. So thats what reactiveValues() help with :). Hope that helps!

Shiny Data table display all data using filter

I can create a data table in shiny that shows data for any individual buffalo but I can't figure out how to display all buffalo data at the same time. Any help is appreciated.
Sample Data:
cleanbuffalo <- data.frame(name = c("queen","toni","pepper"),
longitude = c(31.8,32,33),
latitude = c(-24,-25,-26))
Shiny UI:
shinyUI(navbarPage("Buffalo Migration", id ="nav",
tabPanel("Data",
fluidRow(
column(3,
selectInput("allnamesbuffalo", "Buffalo", c("All Buffalo" = "all buffalo", vars))
)
),
hr(),
DT::dataTableOutput("buffalotable")
)
)
)
Shiny Server:
shinyServer(function(input, output, session) {
observe({
allnamesbuffalo <- if (is.null(input$allnamesbuffalo)) character(0) else {
filter(cleanbuffalo, name %in% input$allnamesbuffalo) %>%
`$`('name') %>%
unique() %>%
sort()
}
})
output$buffalotable <- DT::renderDataTable({
df <- cleanbuffalo %>%
filter(
cleanbuffalo$name == input$allnamesbuffalo,
is.null(input$allnamesbuffalo) | name %in% cleanbuffalo$name
)
action <- DT::dataTableAjax(session,df)
DT::datatable(df, options = list(ajax = list(url = action)),
escape = FALSE)
})
})
Here is a working example. Note that I added stringsAsFactors=F in your data frame, otherwise you need to use levels(cleanbuffalo$name) to get the names.
library(shiny)
library(dplyr)
cleanbuffalo <- data.frame(name = c("queen","toni","pepper"),
longitude = c(31.8,32,33),
latitude = c(-24,-25,-26), stringsAsFactors = F)
ui <- shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
selectInput("allnamesbuffalo", "Buffalo", c("all", cleanbuffalo$name))
),
mainPanel(
dataTableOutput("buffalotable")
)
)
))
server <- shinyServer(function(input, output, session) {
output$buffalotable <- renderDataTable({
names <- NULL
if (input$allnamesbuffalo == "all") {
names <- cleanbuffalo$name
} else {
names <- input$allnamesbuffalo
}
filter(cleanbuffalo, name %in% names)
})
})
shinyApp(ui = ui, server = server)

Resources