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?
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)
}