Create a calendar dimension with the month prior to Sys.date

3

Hello, the script below creates a CSV with a Calendar dimension from year 2015 to the current month. I happen to want the function to return the month before execution. Ex: If Sys.Data records 14/11/2017, it returns the date 10-14-2017. Or, if possible, the date 01/10/2017, since day 01 is the default in this calendar. NOTE: If you prefer, you can suggest creating another script

        tabela_tcm_dCalendario <- list(mes = 1:12, ano = 2015:2017) %>% 
                              purrr::cross_df() %>% 
                              dplyr::mutate(data = as.Date(sprintf("%d-%02d-01", ano, mes))) %>%
                              dplyr::filter(data < Sys.Date())
                              readr::write_csv("parametros_scraping/tabela_tcm_dCalendario.csv")
    
asked by anonymous 14.11.2017 / 19:54

2 answers

2

You can do this:

library(lubridate)
library(dplyr)

data_frame(
  data = seq(ymd("2015-01-01"), (today() - day(today()) + 1 - months(1)), by = "month"),
  ano = year(data),
  mes = month(data)
)

Notice that the (today() - day(today()) + 1 ) - months(1) part returns the first day of the previous month. From this, I used the seq function to create a date string starting January 2015.

    
16.11.2017 / 14:24
3

I added the slice function in your code

list(mes = 1:12, ano = 2015:2017) %>% 
  purrr::cross_df() %>% 
  dplyr::mutate(data = as.Date(sprintf("%d-%02d-01", ano, mes))) %>%
  dplyr::filter(data < Sys.Date()) %>% 
  dplyr::slice(1:(nrow(.)-1))
    
14.11.2017 / 20:11