Marco De Virgilis
Marco De Virgilis

Reputation: 1087

If Cycle in R Shiny

I am trying to write a simple If Cycle in R Shiny but I am founding some issues. I want to create a variable, in this case m, according to what the user inputs. Here there is the code:

if(input$city=="Enter Text..."){


 m<-reactive({leaflet() %>% 
  addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
  addPolylines(data = trips(),
               lng = ~V1, 
               lat = ~V2,weight=1,color="purple") %>%
addCircles(lng = geocode(input$city)$lon, lat = geocode(input$city)$lat, weight = 5,
          radius =input$radius, popup = input$city, color="blue",fillOpacity = 0)
})

} else {

m<-reactive({leaflet() %>% 
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addPolylines(data = trips(),
                 lng = ~V1, 
                 lat = ~V2,weight=1,color="purple")
})
}

In doing this I get an error that says that I am trying to do something outside a reactive environment, but the variable m is defined as reactive. How can I fix this?

Thanks

Upvotes: 0

Views: 384

Answers (1)

sechstein
sechstein

Reputation: 306

input$city is indeed a reactive element which needs to be use in a reactive environment. Just add the if statement inside of your reactive() function. And it will make the code clearer since the beginning of the leaflet construction is the same.

 m<-reactive({leaflet() %>% 
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addPolylines(data = trips(),
                 lng = ~V1, 
                 lat = ~V2,weight=1,color="purple") %>%
    {if(input$city=="Enter Text..."){
          addCircles(., lng = geocode(input$city)$lon, 
          lat = geocode(input$city)$lat, weight = 5,
          radius =input$radius, popup = input$city, 
          color="blue",fillOpacity = 0)
     } else {.}
    }
})

By using addCircles(.,, you get the chaining into the if statement and with else {.}, you just return the previous element, without adding the addCircles function.

Upvotes: 1

Related Questions