I have a simple function and I would like to run it in a forloop
. Many thanks in advance.
library(maps); library(ggplot2)
library(grid); library(sf)
library(dplyr); library(rnaturalearth)
europeanUnion <- c("Austria","Belgium","Bulgaria","Croatia","Cyprus",
"Czech Rep.","Denmark","Estonia","Finland","France",
"Germany","Greece","Hungary","Ireland","Italy","Latvia",
"Lithuania","Luxembourg","Malta","Netherlands","Poland",
"Portugal","Romania","Slovakia","Slovenia","Spain",
"Sweden")
asian.countries <- c("Japan", "China","India", "Thailand",
"South Korea", "North Korea", "Indonesia",
"Philippines", "Singapore", "Vietnam")
#FOR LOOP
my.continents <- c("europeanUnion", "asian.countries")
my.functn <- function(continent.name) {
world_map <- ne_countries(scale = 50, returnclass = 'sf')
my.map <- world_map %>% filter(name %in% continent.name)
ggplot()
geom_sf(data = my.map, fill = 'white')
geom_sf(fill = 'white', alpha = .2)
theme(
panel.background = element_rect(fill = "#666666"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank()
)
}
my.functn(europeanUnion)
for(i in my.continents) {
print(i)
my.functn(i)
}
CodePudding user response:
The main problem is how you define your continents:
my.continents <- c("europeanUnion", "asian.countries")
This means that you loop through a character vector of continent names, rather than the continents that you had defined. You should instead create a list of the vectors you created and loop through that:
my.continents <- list(europeanUnion, asian.countries)
If you just want to print the plots to the console, you can do:
for(continent in my.continents) {
print(continent)
print(my.functn(continent))
}
If you want to save the plot to file then you can do:
for(i in seq_along(my.continents)) {
p <- my.functn(my.continents[[i]])
continent_name <- names(my.continents[i])
outfile <- paste0(continent_name, ".png")
message("Saving to ", outfile)
ggsave(outfile, p, width = 12, height = 7.5)
}
NB: In general in loops it is conventional to use i
as an index number and a name (e.g. continent
) if looping through objects.