I'm trying to add multiple polygon to leaflet world map, according to a number of lists of country code. And I was trying to use R loop to add the polygon. Here's the code that I manually add polygons from list 1:
library(sp)
library(raster)
library(leaflet)
library(maps)
library(tidyverse)
countries_1 <- c('PAK','TUR','BGR')
adm1 <- getData('GADM', country='PAK', level=0)
adm2 <- getData('GADM', country= 'TUR', level=0)
adm3 <- getData('GADM', country= 'BGR', level=0)
leaflet() %>%
addTiles() %>%
addPolygons(data=adm1, weight = 3, fillColor = 'purple', color = 'purple') %>%
addPolygons(data=adm2, weight = 3, fillColor = 'purple', color = 'purple') %>%
addPolygons(data=adm3, weight = 3, fillColor = 'purple', color = 'purple')
I am thinking using the loop to add multiple polygon layers so that for list_n:
countries_n <- ('ctry1','ctry2','ctry3',...'ctryn')
for (i in country_n) {
countries <- basemap %>% addPolygons(data=getData('GADM',country = i, level = 0),
weight = 3, fillColor = 'purple', color = 'purple')
}
The question is how can I embed the loop to "leflet() %>%" ?
*Note here: If try to add multiple data in addPolygons(), it will plot only the first element in the data, in below case, only country 'PAK' will be ploted:
addPolygons(data=c('PAK','TUR'), weight = 3, fillColor = 'purple', color = 'purple')
countries
in a loop pasted string of polygons then just pipe that to the end of yourleaflet%>%addTiles%>%
. You could just paste with the pipe command at the end of each iteration in it inside the loop.... – sconfluentus