Cloud
Cloud

Reputation: 399

Reducing repetitive code for flexdashboard

I am currently using the flexdashboard library to create a dashboard. However, I noticed that there is a lot of repetitive code within the rmarkdown file. An example is as follows:

First repetition

leaflet() %>% 
  addTiles() %>% 
  fitBounds(103.664712, 1.411486, 104.02233, 1.24164) %>%
  addCircleMarkers(raw_data_n2$lng, 
                 raw_data_n2$lat,
                 color = raw_data_n2$col_n2_vacancy,
                 radius = 2, 
                 fill = T,

 fillOpacity = 0.2,
                 opacity = 0.6,
                 popup = paste(raw_data_n2$centre_name, 
                               sep="")) %>%
  addLegend("bottomleft", 
            colors = c("red", "yellow", "green"),
            labels = c("No vacancies for the next 1-2 years",
                       "Vacancies within 6 months",
                       "Immediate vacancies"), 
            opacity = 0.8)

Second repetition

leaflet() %>% 
  addTiles() %>% 
  fitBounds(103.664712, 1.411486, 104.02233, 1.24164) %>%
  addCircleMarkers(raw_data_k1$lng, 
                 raw_data_k1$lat,
                 color = raw_data_k1$col_k1_vacancy,
                 radius = 2, 
                 fill = T,
                 fillOpacity = 0.2,
                 opacity = 0.6,
                 popup = paste(raw_data_k1$centre_name, 
                               sep="")) %>%
  addLegend("bottomleft", 
            colors = c("red", "yellow", "green"),
            labels = c("No vacancies for the next 1-2 years",
                       "Vacancies within 6 months",
                       "Immediate vacancies"), 
            opacity = 0.8)

Is there a way of changing this code within the rmarkdown such that this repetition is reduced?

Upvotes: 0

Views: 60

Answers (1)

demarsylvain
demarsylvain

Reputation: 2185

One option is to create a function, with your repetitive code, and call it each time you need it.

myOwnLeaflet <- function(df){

  df %>% 
    leaflet() %>% 
    addTiles() %>% 
    fitBounds(103.664712, 1.411486, 104.02233, 1.24164) %>%
    addCircleMarkers(
      df$lng, 
      df$lat,
      color = df$col_n2_vacancy,
      radius = 2, 
      fill = T,
      fillOpacity = 0.2,
      opacity = 0.6,
      popup = paste(centre_name, sep = "")
    ) %>%
    addLegend(
      "bottomleft", 
      colors = c("red", "yellow", "green"),
      labels = c("No vacancies for the next 1-2 years",
                 "Vacancies within 6 months",
                 "Immediate vacancies"), 
      opacity = 0.8)

}

Upvotes: 2

Related Questions