Issues dealing with dates

Hi Everyone! I am new in the Data Analyst´s world and I am working in my first project, but im having some trouble dealing with dates in the data frame that I have created. The problem is that R is changing the dates and I dont understand why. 'Im pretty sure that is a roockie error and I hope someone of the community can help me.

#First I created the data frame (previosly loaded tidyverse and lubridate)

Date <- c(2004-01-01, 2005-01-01, 2006-01-01, 2007-01-01, 2008-01-01, 2009-01-01, 2010-01-01, 2011-01-01, 2012-01-01, 2013-01-01, 2014-01-01, 2015-01-01, 2016-01-01, 2017-01-01, 2018-01-01, 2019-01-01, 2020-01-01)
Inflation <- c(0.1836, 0.1031, 0.1374, 0.1494, 0.2317, 0.1538, 0.2091, 0.2370, 0.2231, 0.2395, 0.4028, 0.2658, 0.4112, 0.2601, 0.4001, 0.5062, 0.3984)
inflation.argentina <- data.frame(Date, Inflation)

#After that I wrote the head() function and something weird happen with the dates (starts in 2002 instead of 2004 and only shows the year).

head(inflation.argentina)

After that, I've changed the class hoping to fix this error but I keep having the wrong dates (Now it show the full date but it starts in 2009-06-25 and with one-day progression instead of one-year progression)

inflation.argentina$Date <- as.Date(inflation.argentina$Date, origin = "2004-01-01")
head(inflation.argentina)

By writing 2004-01-01 you are doing a numeric calculation; two thousand and four minus one minus one. You can convert the characters "2004-01-01" to dates in a few ways. The code below illustrates what you originally did, a couple of functions for changing characters into dates, and using the seq.Date function to generate a long series of dates .

#This results in numbers
Date <- c(2004-01-01, 2005-01-01)
Date
#> [1] 2002 2003
class(Date)
#> [1] "numeric"

#Converting characters to dates
Date2 <- as.Date(c("2004-01-01", "2005-01-01"))
Date2
#> [1] "2004-01-01" "2005-01-01"
class(Date2)
#> [1] "Date"

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
Date2_1 <- ymd(c("2004-01-01", "2005-01-01"))
Date2_1
#> [1] "2004-01-01" "2005-01-01"
class(Date2_1)
#> [1] "Date"


#save typing usint seq.Date
Date3 <- seq.Date(from = as.Date("2004-01-01"), to = as.Date("2006-01-01"), by = "year")
Date3
#> [1] "2004-01-01" "2005-01-01" "2006-01-01"
class(Date3)
#> [1] "Date"

Created on 2021-07-29 by the reprex package (v0.3.0)

1 Like

It works! Thank you so much!. I have spent hours trying to solve the issue by myself, so I really appreciate it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.