R:如何使用应用创建多个地图(rworldmap)?

R: How to create multiple maps (rworldmap) using apply?

我想使用 apply 系列创建多个地图(类似于 this 示例)。这是我的一小部分代码示例(~200 行 x 150 列)。 (UN和ISO3是rworldmap的代码):

df <- structure(list(BLUE.fruits = c(12803543, 
    3745797, 19947613, 0, 130, 4), BLUE.nuts = c(21563867, 533665, 
    171984, 0, 0, 0), BLUE.veggies = c(92690, 188940, 34910, 0, 0, 
    577), GREEN.fruits = c(3389314, 15773576, 8942278, 0, 814, 87538
    ), GREEN.nuts = c(6399474, 1640804, 464688, 0, 0, 0), GREEN.veggies = c(15508, 
    174504, 149581, 0, 0, 6190), UN = structure(c(4L, 5L, 1L, 6L, 
    2L, 3L), .Label = c("12", "24", "28", "4", "8", "n/a"), class = "factor"), 
    ISO3 = structure(c(1L, 3L, 6L, 4L, 2L, 5L), .Label = c("AFG", 
    "AGO", "ALB", "ASM", "ATG", "DZA"), class = "factor")), .Names = c("BLUE.fruits", "BLUE.nuts", "BLUE.veggies", "GREEN.fruits", "GREEN.nuts", 
    "GREEN.veggies", "UN", "ISO3"), row.names = c(97L, 150L, 159L, 
    167L, 184L, 191L), class = "data.frame")

以及我之前用来绘制一张地图的代码:

library(rworldmap)
mapDevice('x11')
spdf <- joinCountryData2Map(df, joinCode="ISO3", nameJoinColumn="ISO3")     
mapWF <- mapCountryData(spdf, nameColumnToPlot="BLUE.nuts", 
               catMethod="quantiles")

注意:在 mapCountryData() 中,我使用了单个列的名称(在本例中为 "BLUE.nuts")。我的问题是:有没有办法 apply 此映射代码为不同的列创建六个不同的映射?要么在一个多面板中使用 layout(),要么更好地创建六个不同的图,这些图根据它们的名称保存。想法?非常感谢

你很接近。

添加此项以每列保存一个图。

#put column names to plot in a vector
col_names <- names(df)[1:6]


lapply(col_names, function(x) {
  #opens device to store pdf
  pdf(paste0(x,'.pdf'))
  #plots map
  mapCountryData(spdf, nameColumnToPlot=x)
  #closes created pdf 
  dev.off()
})