Hi
I am having trouble with the ifelse function on a raster image in shiny. Can anyone help me in this regard? Here is a reproducible code for the problem.
library(shiny)
library(leaflet)
library(raster)
library(rgdal)
library(mapview)
xy <- matrix(runif(400),20,20)
rst <- raster(xy)
extent(rst) <- c(-152,-150 ,66,68)
projection(rst) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
names(rst) <- 'ndvi_map'
#map <- leaflet() %>% addProviderTiles("Esri.WorldImagery") %>%
#setView(lng = -152, lat = 67.5, zoom =7) %>%
#addMouseCoordinates(style = "basic")
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(top = 10, right = 10,
sliderInput("ndvi_map", "ndvi", min= 0, max= 1,
value = 0.5, step = 0.1)
#checkboxInput("legend", "Show legend", TRUE)
)
#mainPanel(leafletOutput('Raster', width = "100%", height = "100%"))
)
server <- function(input, output, session) {
filterData <- reactive({
calc(rst[[input$ndvi_map]], fun = function(x){
ifelse(is.na(x) == T, NA,
ifelse(x >=input$ndvi_map[1] & x <=input$ndvi_map[2], x, NA))})
})
#})
pal <- colorNumeric("RdYlBu", values(rst),
na.color = "transparent")
output$map <- renderLeaflet({
leaflet() %>% addProviderTiles("Esri.WorldImagery") %>%
setView(lng = -152, lat = 67.5, zoom =7) %>%
addMouseCoordinates(style = "basic")%>%
addRasterImage(filterData(), colors = pal, opacity = 1) %>%
addLegend(position = "bottomright", pal = pal, values = values(rst),
opacity = 1)
#observe({
#leafletProxy('map_rst') %>%
#clearImages() %>%
#addRasterImage(filterData(), colors = pal, opacity = 1, layerId = input$range)
#})
})
}
shinyApp(ui, server)
Listening on http://127.0.0.1:4791
Warning: Error in inherits: not a valid subset