We want two things:
- figure out what month is X months ago
- format that date into a file name string we can use
Here's a function to do those two things:
library(lubridate)
file_namer <- function(months_prior) {
current_month <- floor_date(Sys.Date(), "month")
dest_month <- current_month %m-% months(months_prior)
paste0("R:/", year(dest_month), "_", month(dest_month), "_F2.csv")
}
floor_date(Sys.Date(), "month") will output the 1st of the current month. I calculate that to avoid any complications around different-length months. All months have a 1st so that should be predictable.
Then I use lubridate's odd-looking %m-% operator which subracts months (basically equivalent to using negative numbers with Excel's EDATE function, as far as I can tell).
Finally, I paste the results together into a string like we need.
We can test it out:
file_namer(0)
[1] "R:/2021_4_F2.csv"
file_namer(12)
[1] "R:/2020_4_F2.csv"
file_namer(36)
[1] "R:/2018_4_F2.csv"
We could use it like
DATAFRAMEINPUT <- read.csv2(filenamer(36), header=TRUE)
DATAFRAMEINPUT <- read.csv2(filenamer(35, header=TRUE)
DATAFRAMEINPUT <- read.csv2(filenamer(34), header=TRUE)
(I assume you are actually saving the results to different files, otherwise the 2nd line will just overwrite the result of the 1st line, and then again with the 3rd line.)