我有一個簡單的功能,我想在forloop. 提前謝謝了。
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)
}
uj5u.com熱心網友回復:
主要問題是你如何定義你的大陸:
my.continents <- c("europeanUnion", "asian.countries")
這意味著您回圈遍歷大陸名稱的字符向量,而不是您定義的大陸。相反,您應該創建一個您創建的向量串列并回圈遍歷:
my.continents <- list(europeanUnion, asian.countries)
如果您只想將繪圖列印到控制臺,您可以執行以下操作:
for(continent in my.continents) {
print(continent)
print(my.functn(continent))
}
如果要將繪圖保存到檔案,則可以執行以下操作:
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)
}
注意:通常在回圈中,如果回圈遍歷物件,通常將其i用作索引號和名稱(例如)。continent
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512542.html
上一篇:基于可變資料分布填充缺失資料
下一篇:如何為Rcpp將R轉換為C
