1

I am referring to the choropleth tutorial for Leaflet (https://rstudio.github.io/leaflet/choropleths.html) and modifying it for Shiny. I have different columns that I want to be able to use depending on what the user selects. The problem I encounter has to do with this part:

pal <- colorBin("YlOrRd", domain = states$density, bins = bins)

m %>% addPolygons(
  fillColor = ~pal(density),
  weight = 2,
  opacity = 1,
  color = "white",
  dashArray = "3",
  fillOpacity = 0.7)

Specifically, I want to be able to replace the density column be a column that I can get from a button in Shiny (assume the columns are called a and b and that I get them from the name_button object). I create the col_name function to enclose this choice:

col_name <- reactive({
  name <- switch(input$name_button, "A" = "a", "B" = "b" )
  name})

Then I can modify the pal <- ... line as follows (see R how use a string variable to select a data frame column using $ notation):

pal <- colorBin("YlOrRd", domain = states[[col_name()]], bins = bins)

However, I am not sure how to change the fillColor = ~pal(density), line because density is the name of a column. I have tried

fillColor = ~pal([[col_name]])

but this doesn't work. What can I do?

Also, what is the function of the tilde ~ in ~pal(...)?

Community
  • 1
  • 1
bill999
  • 2,147
  • 8
  • 51
  • 103
  • 1
    Try this: `fillColor = ~ pal(states[[col_name]])`? For the tilde sign, maybe you can read [this](http://stackoverflow.com/questions/14976331/use-of-tilde-in-r-programming-language)? I think for `~ pal(density)`, `pal()` is a function that takes the number (density) and returns a color index. – lao_zhang Apr 14 '17 at 05:51
  • This works. The only change (and I should have done this too) is to add `()` after `col_name` because it is a function: `fillColor = ~ pal(states[[col_name()]])`. But the key point of having `states` in front holds. Thanks for the help! – bill999 Apr 14 '17 at 13:12

0 Answers0