Create a calendar dimension with the month before Sys.date.

Asked

Viewed 195 times

3

Hello, the scrip below creates a CSV with a Calendar dimension from the year 2015 to the current month. It turns out that I would like the function to return the month before the execution. Ex: If Sys.Data registers 14/11/2017, it returns the date 14/10/2017. Or, if possible, the date 01/10/2017, since the day 01 is the standard on this dCalegendary. 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")

2 answers

3

I added the function slice 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))
  • Thank you very much. The suggestion was very good

2


You can do it like 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)
)

See that part (today() - day(today()) + 1 ) - months(1) returns the first day of the previous month. From that, I used the function seq to create a sequence of dates from January 2015.

  • Thank you very much. The script is excellent. I ended up replacing mine. This final part, I confess that I still have to study a little more to understand. I’m starting in the R has about 1 month.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.