user14443915
user14443915

Reputation:

Change numeric vector into specific date

I have got a vector like 0 20 365 390 and would like to convert into the date that would occur if that many days has passed so for some origin day (2007-01-01) would be 2007-01-01 2007-01-21 2008-01-01 2008-02-26. How would I quickly do that in R?

Upvotes: 0

Views: 27

Answers (2)

mnist
mnist

Reputation: 6954

Even though it is not necessary in this case when dealing just with days, it is always a good idea to point at the lubridate package when dealing with dates/time:

library(lubridate)

start_date <- as_date("2007-01-01")
my_vec <- c(0, 20, 365, 390)

start_date + days(my_vec)
#> [1] "2007-01-01" "2007-01-21" "2008-01-01" "2008-01-26"

# easily adding months:
start_date + months(my_vec)
#> [1] "2007-01-01" "2008-09-01" "2037-06-01" "2039-07-01"

Upvotes: 0

MarBlo
MarBlo

Reputation: 4534

You can do this like so:

dat <- as.Date('2007-01-01') 
dat + c(0,20, 365, 390)
#> [1] "2007-01-01" "2007-01-21" "2008-01-01" "2008-01-26"

You will discover that the last element of the result is different to your expected output.

Upvotes: 2

Related Questions