Folks, really simple q about simple Shiny app.
I receive a strange error NAs not permitted in row index
# Load packages
library(shiny)
library(rgdal)
library(raster)
library(leaflet)
library(sp)
library(geojsonio)
library(RColorBrewer)
library(jsonlite)
library(shinythemes)
# Global code
# Read file on a local machine
data_pg <- read.csv("pg.csv", header = TRUE, stringsAsFactors = FALSE)
# Read a shapefile
countries <- readOGR(".","ne_50m_admin_0_countries")
# Merge data
data_pg_df <- merge(countries, data_pg, by.x = "NAME", by.y = "Country", duplicateGeoms = TRUE)
# UI code
ui <- fluidPage(theme = shinytheme("united"),
titlePanel("PG Map"),
sidebarLayout(
sidebarPanel(
selectInput("regionInput", "Region",
choices = c("Choose region",
"Africa",
"Asia",
"Latin America",
"North America",
"Europe"),
selected = "Choose region"),
selectInput("pgInput", "Select PG",
choices = c("Choose PG",
"PG 1",
"PG 2",
"PG 3"),
selected = "Choose PG")
),
mainPanel(
# Output
tabsetPanel(type = "tabs",
tabPanel("Map", leafletOutput(outputId = 'map', height = 700)) #,
# tabPanel("Chart", plotOutput("chart")),
# tabPanel("Table", tableOutput("table"))
)
)
)
)
# Server
server <- function(input, output) {
selectedRegion <- reactive({
data_pg_df[data_pg_df$Region == input$regionInput, ]
})
output$map <- renderLeaflet({
leaflet(data_pg_df) %>%
addProviderTiles(providers$Stamen.Toner) %>%
addPolygons(stroke = FALSE,
fillOpacity = 0.75,
color = pal(selectedRegion()), weight = 1)
})
}
shinyApp(ui = ui, server = server)
I got this advise on SO.
Using View(data_pg_df)
you will find data_pg_df
is an S4 class and to subset S4 you need to use @
. Also, I think you have a problem with merge as you can see in View(data_pg_df@data)
. This will works
data_pg_df@data[data_pg_df@data$Region == input$regionInput, ]
With warning:
Warning in pal(selectedRegion()) : Some values were outside the color scale and will be treated as NA
But it does not resolve my problem, unfortunately. Filter does not work and map still sucks.
Any help is very much appreciated. Thanks!