as.Date and srtptime commands in R

3

Suppose the following vector:

datas=c("26/12/2014", "27/12/2014", "28/12/2014", "29/12/2014", "30/12/2014", "31/12/2014")

When you apply the commands as.Date(datas, "%d/%m%y") and strptimes(datas, "%d/%m%y") the output is:

"2020-12-26" "2020-12-27" "2020-12-28" "2020-12-29" "2020-12-30" "2020-12-31"

Why is the Year (y) wrong? How do I adjust this?

    
asked by anonymous 15.09.2015 / 16:22

3 answers

2

You need to use the command:

as.Date(datas, "%d/%m/%Y")

Note the %Y in upper case. It indicates that the year is in four digits. When you use %y tiny, he understands that the year has only two digits and so it puts 2020.

    
15.09.2015 / 16:56
2

You must use the upper Y, to indicate that the year format has 4 digits.

datas=c("26/12/2014", "27/12/2014", "28/12/2014", "29/12/2014", "30/12/2014", "31/12/2014")

as.Date(datas, "%d/%m/%Y") 
#[1] "2014-12-26" "2014-12-27" "2014-12-28" 
#[4] "2014-12-29" "2014-12-30" "2014-12-31"

strptime(datas, "%d/%m/%Y") 
#[1] "2014-12-26 BRST" "2014-12-27 BRST" "2014-12-28 BRST" 
#[4] "2014-12-29 BRST" "2014-12-30 BRST" "2014-12-31 BRST"
    
15.09.2015 / 16:56
2

The function dmy of lubridate can interpret dates considering what they see as (day, month, year):

library(lubridate)
dmy(datas)
# [1] "2014-12-26 UTC" "2014-12-27 UTC" "2014-12-28 UTC" "2014-12-29 UTC" "2014-12-30 UTC"
# [6] "2014-12-31 UTC"

The same goes for ymd and other variations.

    
17.09.2015 / 17:59