How to parallelize the do.call function

Question:

I need to assemble multiple rasters to a single raster . Both the raster::merge and raster::mosaic functions work fine in this situation, but I need to do a do.call to call the function to assemble the multiple rasters that are in a list.

How to do this in parallel? How to make do.call faster?

require(raster)
r <- raster(ncol=100, nrow=100)
r1 <- crop(r, extent(-10, 11, -10, 11))
r1[] <- 1:ncell(r1)
r2 <- crop(r, extent(0, 20, 0, 20))
r2[] <- 1:ncell(r2)
r3 <- crop(r, extent(9, 30, 9, 30))
r3[] <- 1:ncell(r3)
rast.list <- list(r1, r2, r3)     
rast.list$fun <- mean
rast.mosaic <- do.call(mosaic,rast.list)

Answer:

To parallelize a function, you can use the purrr package.

The map2 function is for taking several arguments in a function at once:

library(tidyverse)
a = c("Eu sou o Igor.", "Eu sou o João.")
b = c(" Eu gosto disso.", " Eu gosto daquilo.")

map2(a, b, ~stringr::str_c(.x, .y))
#[[1]]
#[1] "Eu sou o Igor. Eu gosto disso"

#[[2]]
#[1] "Eu sou o João. Eu gosto daquilo"

See what's happening. The value a is being applied as the first argument to the str_c function. The value b is being applied as the second argument.

You can use map2_chr to return an array of characters:

map2(a, b, ~stringr::str_c(.x, .y))
#[1] "Eu sou o Igor. Eu gosto disso"   "Eu sou o João. Eu gosto daquilo"
Scroll to Top