我当前正在使用flexdashboard库创建仪表板。但是,我注意到rmarkdown文件中有很多重复的代码。一个例子如下:
首次重复
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)
第二次重复
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)
是否有一种方法可以在rmarkdown中更改此代码,从而减少重复次数?
答案 0 :(得分:2)
一种选择是使用重复代码创建一个函数,并在每次需要时调用它。
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)
}