Using the file.copy() function to copy files into a new folder with column names from a data table

Hey y'all, need your help figuring this one out. I managed to construct a data table in R which listed all 176 of my PNG outmap maps by filename, year, month, and day considering they were labeled as such, "Avg_monthly_2005_06_01.png" as an example. I can filter the data table to spit out only desired years such as 2006 or 2010, however, I am struggling at the next step of creating a GIF from those specific PNGs.

One fellow RStudio person recommended using file.copy() by calling the filename column of my data column and moving specific years (let us say only the 2006 PNG output maps) into a specific folder. From there, it is easy enough to construct a GIF. Does anyone know how to code this? I am stuck on trying to find a way to write a line of code that can let me use the filename column of my data table to call file.copy() and move those files into another folder in my working directory.

Here is my code below if that helps:
file_list <- list.files("C:/Users/Documents/gifmonthlybarca/barca_monthly")
file_list

dataframe <- tibble(my_filenames = file_list) %>%
mutate(fields = strsplit(file_list, "_"),
date_fields = map(fields, ~ .x[(length(.x)-2): length(.x)]),
year = map_chr(date_fields, ~ .x[1]),
month = map_chr(date_fields, ~ .x[2]),
day = map_chr(date_fields, ~ .x[3]),
year = as.integer(year),
month = as.integer(month),
day = as.integer(day)) %>%
select(my_filenames, year:day)

barca_2006 <- filter(dataframe, year == "2006")

file.copy won't do exactly what you want; this should illustrate:

dir.create("png_folder")
dir.create("gif_folder")

file.create("png_folder/1.png")
file.create("png_folder/2.png")
file.create("png_folder/3.png")

files <- tibble(file_name_with_extension = list.files("png_folder"),
                file_path_with_extension = list.files("png_folder", full.names = TRUE)) %>%
  mutate(file_name_without_extension = str_remove(file_name_with_extension, ".png"))

purr::walk2(files$file_path_with_extension, files$file_name_without_extension, ~file.copy(paste0(.x), paste0("gif_folder/", .y, ".gif")))

The walk2 part does what you asked for - call file.copy iteratively for each file - but it doesn't convert the file from a PNG to a GIF; it just renames the .png file with .gif; it's still a PNG!

Since you said GIFs, did you want the PNGs to be combined into a single animated GIF (in which case look into the magick package), or would you like each PNG to become a single GIF (in which case look into the imager package)?

Hope that's helpful!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.