我有一个功能,每年创建每个国家的鱼类捕获图,并将该地图放入地图列表中,这取决于我喂食的年份:
fishtogram <- function(year) {
dfname <- paste0("carto", year) # name of the cartogram being made
map_year <- get(paste0("map", year), map_years) # 'map_year' contains one SpatialPolygonsDataFrame of a year of fishing/country data pulled from the list of spdf's 'map_years'
carto_maps[[dfname]] <<- cartogram(map_year, "CATCH", itermax=1) # This is the part that takes forever. Create cartogram named 'dfname', chuck it into the carto_maps list
plot(carto_maps[[dfname]], main=dfname) # plot it
print(paste("Finished", dfname, "at", Sys.time())) # print time finished cartogram
writeOGR(obj = carto_maps[[dfname]], dsn = "Shapefiles", layer = dfname, driver = "ESRI Shapefile", overwrite_layer=TRUE) # Save cartogram as shapefile
}最初,这一切都是在一个for循环(1950年至2014年),它做的工作,只是极其缓慢。减慢我速度的部分是cartogram函数。目前,制作一张地图需要大约一个小时,使用大约13%的CPU。我想尝试和使用并行处理,使3-4地图在一次,并希望加快速度。
如何将它正确地封装在一个应用函数中,以便在我想要的时间内对这两个循环进行处理,并使用并行处理?我一直在使用这是R博客的帖子作为指导。我的尝试:
lapply(seq(1975, 2014, 10), fishtogram, .parallel=TRUE)
>Error in FUN(X[[i]], ...) : unused argument (.parallel = TRUE)谢谢@patL告诉我使用lapply vs apply。
我的代码和数据可以在这里找到:cartograms.R
发布于 2018-02-07 21:47:53
为了并行,您可以从parapply库中尝试一些parallel家族函数。
下面是这页面中的步骤,您将需要第一次检测核心的数量:
library(parallel)
no_cores <- detectCores() - 1 #it is recomendable that you use the number of cores less one
cl <- makeCluster(no_cores) #initiate cluster导出在并行化过程中将使用的所有函数和对象是很重要的:
clusterExport(cl, "fishtogram")
clusterExport(cl, "dfname")
clusterExport(cl, "map_years")
...然后可以运行并行化版本的lapply。
parLapply(cl, seq(1975, 2014, 10), fishtogram)并最终停止集群
stopCluster(cl)还有其他可以并行运行代码的函数(foreach,来自foreach库;mclapply,也来自parallel库,等等)。
发布于 2018-02-07 20:31:00
您的具体错误来自于鱼图函数的括号。您在使用apply时不需要它们:
apply(seq(1975, 2014, 10), 1, fishtogram)..would修复了这个错误。
https://stackoverflow.com/questions/48672679
复制相似问题