user5879741
user5879741

Reputation: 27

Add yyyy-mm to excel output file name in R

I'm currently saving an excel file as "Fin_report.xlsx", but I would like to incorporate the dates at which it was saved, too. It should look something like: "Fin_report-yyyy-mm.xlsx"

where yyyy-mm is the date of last month. For example, if today is 2018-03-01, then today's file should be saved as: "Fin_report-2018-02.xlsx"

Upvotes: 0

Views: 1121

Answers (2)

KenHBS
KenHBS

Reputation: 7164

Using only base R, you can get the current time on your computer with Sys.Date(). You can 'reduce' one month using a cool feature of seq(), this will give you:

lastmonth <- seq(Sys.Date(), length=2, by="-1 months")[2]
# [1] "2018-02-01"

You can extract only the month and years using format:

format(lastmonth, "%Y-%m")
# [1] "2018-02"

Then you can use paste0 to format a string as a filename:

filename <- paste0("Fin_report-", format(lastmonth, "%Y-%m"), ".xlsx")
filename 
# [1] "Fin_report-2018-02.xlsx"

Upvotes: 0

David
David

Reputation: 10192

What you are looking for is a mixture of changing the month of a date and inserting a string into another one.

I would do it like this using the lubridate library for dates and by writing my own function last_month(), that prints us the month from last month.


library(lubridate)

# A small function that prints the date 
# of the last month in the YYYY-MM format
last_month <- function(d = today()) {
  day(d) <- 1
  month(d) <- month(d) - 1
  format(d, "%Y-%m")
}

# lets try it
last_month()
#> [1] "2018-02"


file <- "Fin_report.xlsx"

# replace the .xlsx with -YYYY-MM.xlsx
file2 <- gsub("\\.xlsx$", paste0("-", last_month(), ".xlsx"), file)

file2
#> [1] "Fin_report-2018-02.xlsx"

Upvotes: 1

Related Questions