I'm trying to create a vector of dates for, say, the period from January 1, 2018 to October 31, 2019 using base R. What I can think of is to first create that vector using the seq
and functions as.Date
as follows:
fecha <- data.frame(fecha=seq(from = as.Date("2018-01-01", format="%Y-%m-%d"),
to = as.Date("2019-10-31", format="%Y-%m-%d"), by = 1))
Which returns the following:
str(fecha)
## $ fecha: Date, format: "2018-01-01" "2018-01-02"
Now, we commonly use the day-month-year format, and, to have that format, we use the function format
.
fecha[,"fecha"] <- format(fecha[,"fecha"], "%d-%m-%Y")
str(fecha)
'data.frame': 669 obs. of 1 variable:
$ fecha: chr "01-01-2018" "02-01-2018" "03-01-2018" "04-01-2018" ...
The format is the desired one but the dates are now of character type. If I try to coerce using again as.Date
I pretty much go back to the beginning:
fecha[,"fecha"] <- as.Date(fecha[,"fecha"], format="%d-%m-%Y")
str(fecha)
'data.frame': 669 obs. of 1 variable:
$ fecha: Date, format: "2018-01-01" "2018-01-02" ...
Any solution to this problem? I am interested in having one based on R and I would appreciate any additional solution (I understand that the libraries allow zoo
you lubridate
to work with dates, although I honestly don't know their main functions)
Thanks in advance for any guidance.
The first point I want to make is:
In the case of a
Date
, the data itself is a number that represents the number of days since 1/1/1970.The data could be said to be format agnostic. The representation to the user is the one that could eventually have a certain format. A data
Date
is represented by the functionprint.Date()
that does not establish any special format, so the default format is used,format.POSIXlt()
which is precisely the least ambiguous format, ISO, that is,yyyy-mm-dd
. If you want to modify this, the good practice is to use itformat
with the desired format, the conversion to a string is the only way to display this data, keep the data with the original class and only use theformat
to display it to the user. But the only way, would be modifying the base functionprint.Date()
so that it uses a specific format, this, in any case, is something potentially dangerous, I say modifying a base routine, it has its risks:With the code above, effectively, every time you display a date, you will see it in the new format: