Reputation: 563
I am trying to understand purrr, and how to map/walk over a list of images and save them to files. Below is my code that works using a for loop, but how would this be structured using purrr? I am confused by the various versions (walk, walk2, pwalk, map, map2, pmap etc.)
library(magick)
library(purrr)
#create a list of the files
inpath <- "C:\\Path\\To\\Images"
file_list <- list.files(path = inpath, full.names = TRUE)
# read the files and negate them
imgn <- map(file_list, image_read) %>%
map(image_negate)
# assign list names as original file names
names(imgn) = list.files(path = inpath)
# how to use walk, map, map2? walk2, pwalk? to do this
for (i in 1:length(imgn)) {
image_write(imgn[[i]], path = names(imgn)[[i]])
}
Upvotes: 0
Views: 449
Reputation: 887691
Using Map
from base R
Map(function(x, y) image_write(x, path = y), imgn, file_list)
Upvotes: 2
Reputation: 1298
If I'm correct in understanding your code, it looks like you're trying to save your edited images to their original file paths. If so, could you replace your for loop with:
map2(imgn, file_list, ~ image_write(.x, path = .y))
As an explanation, you want to use map2
because you're applying a function with two inputs; the image you're saving (stored in imgn
), and the filepath you're writing it to (stored in file_list
). You can then use formula notation to specify the function and arguments you'd like to map, as above (more on this in the map
docs).
Upvotes: 1