title: Sort legend (for colorFactor) using leaflet package (RStudio) in Shiny App
body: <p>I'm deploying a shinyapp using the new leaflet package developed by RStudio. There doesn't appear to be much documentation online about some elements - in my case, I need to specify the order in which the legend displays the factor levels. Normally, I would do this (e.g. in ggplot2) by specifying the levels in advance of the plotting command as:</p>
  
  <pre><code>df$name &lt;- factor(df$name, levels = sort(df$name))
  </code></pre>
  
  <p>However, this doesn't seem to work with the legend in leaflet. Below is a MWE (N.B. Africa geojson file can be downloaded <a href="https://dl.dropboxusercontent.com/u/27571064/africa.geo.json" rel="noreferrer">here</a>). You will see that the legend order is not alphabetically sorted, as one would normally expect. My question is how one could do this.</p>
  
  <pre><code>library(shiny)
  library(leaflet)
  
  map_africa &lt;- rgdal::readOGR("africa.geo.json", "OGRGeoJSON")
  
  map_africa$name &lt;- factor(map_africa$name, levels = sort(map_africa$name))
  
  ui &lt;- bootstrapPage( leafletOutput("map") )
  
  server &lt;- function(input, output, session) {
  
    pal &lt;- colorFactor('RdYlBu', map_africa$name)
  
    output$map &lt;- renderLeaflet({ 
  
      leaflet(map_africa) %&gt;% 
      addPolygons(stroke = F,
                  fillColor = ~pal(name),
                  popup = ~name) %&gt;% 
      addLegend(position = 'topright',
                colors = ~pal(name), 
                labels = ~name) 
  
    })
  
  }
  
  shinyApp(ui, server)
  </code></pre>