Reputation: 2351
When I export files from R, I add a timestamp. I created some example data below
library(readxl)
mtcars2 <- mtcars
mtcars2$carb <- NULL
timestamp <- format(Sys.time(), "%d %m %Y %Hh")
timestamp <- gsub(" ", "_", timestamp)
write_xlsx(mtcars, path = paste0(path_in, "mtcars_timestamp_", timestamp, ".xlsx"), col_names = TRUE)
write_xlsx(mtcars2, path = paste0(path_in, "mtcars_timestamp_", timestamp, ".xlsx"), col_names = TRUE)
timestamp <- "07_12_2022_11h"
write_xlsx(mtcars, path = paste0(path_in, "mtcars_timestamp_", timestamp, ".xlsx"), col_names = TRUE)
timestamp <- "06_12_2022_13h"
write_xlsx(mtcars2, path = paste0(path_in, "mtcars2_timestamp_", timestamp, ".xlsx"), col_names = TRUE)
The downside of this approach is that I have to update the files names when I load them into R.
I was wondering if there is a way to make R automatically upload the latest version of a file.
Desired_output:
mtcars2 <- read_xlsx("mtcars2_timestamp_06_12_2022_10h.xlsx")
mtcars <- read_xlsx("mtcars_timestamp_07_12_2022_11h.xlsx")
Upvotes: 0
Views: 58
Reputation: 58
You can use the Fs package to take a look at your file structure and pull the file with the most recent upload date. Then dynamically run this result through your read_xlsx function.
# Install and load the "fs" package
install.packages("fs")
library(fs)
path = "/path/to/directory"
# Get the modification time for each file
files = dir_ls(path)
# Get the modification times for each file
times = file.info(files)$mtime
# Find the index of the file with the latest modification time
index = which.max(times)
# Print the name of the latest file
print(files[index])
read.xlsx(files[index])
Upvotes: 1