# Create a monthly adjustable program

I have the following code:

Instead of 2018_01 I want n-36, i.e., the 36th previous month.
Instead of 2018_02 I want n-35, i.e., the 35th previous month.
Instead of 2018_03 I want n-34, i.e., the 34th previous month.

I want to define a base month on the code and then count backwards 36 months.

I want to create a monthly routine program.

Can you help me writing the proper code?

We want two things:

1. figure out what month is X months ago
2. 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

(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.)

I have run this code and solved the problem.

# Defining Variables
MESANALISE <- "01_2021"
# MESINICIAL - Substituir na linha 16 o primeiro dia desse mês
FLUXO <- "F1"
FLUXO2 <- "FL1"

# Creates a vector with the name of the 36 files to import
DATAFRAMEINPUTFILES <- seq(from = as.Date("2018/01/01"),
by = "month",
length.out = 36)
DATAFRAMEINPUTFILES <- substr(DATAFRAMEINPUTFILES, 1, 7)
DATAFRAMEINPUTFILES <- paste(substr(DATAFRAMEINPUTFILES, 6, 7), substr(DATAFRAMEINPUTFILES, 1, 4), sep = "_")
DATAFRAMEINPUTFILES <- paste0("R:/", FLUXO2, "/", DATAFRAMEINPUTFILES, "_", FLUXO, ".csv")

# Import the files
for(i in 1:length(DATAFRAMEINPUTFILES)) {
assign(paste0("DATAFRAMEINPUT_COM_TT_N_", i),