将 yyyy-mm 添加到 R 中的 excel 输出文件名



我目前正在将 excel 文件保存为"Fin_report.xlsx",但我也想合并保存它的日期。它应该看起来像这样:"Fin_report-yyyy-mm.xlsx"

其中yyyy-mm是上个月的日期。例如,如果今天是 2018-03-01,则今天的文件应另存为:"Fin_report-2018-02.xlsx"

您正在寻找的是更改日期月份和将字符串插入另一个日期的混合。

我会使用lubridate库来获取日期,并通过编写我自己的函数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"

仅使用基本 R,您可以使用Sys.Date()获取计算机上的当前时间。您可以使用seq()的酷炫功能"减少"一个月,这将为您提供:

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

您可以使用format仅提取月份和年份:

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

然后,您可以使用paste0将字符串格式化为文件名:

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

最新更新