Dwdata2b
Dwdata2b

Reputation: 25

R date variable operation

I have a string/character variable contains a calendar date, eg,

x <- "2018-10-31"

I also have a variable y contains time, say 200 days.

y <- 200

How do I find out the calendar date for x + y?

I am not familiar with date type in R and struggle with how to approach this.

An add-on question, would this calculation be different if y = 4.3 months? Of course I can convert this into days, though wonder if there is more direct way to handle months without converting.

Upvotes: 0

Views: 73

Answers (1)

Nautica
Nautica

Reputation: 2018

You could utilise the lubridate package, which is specifically designed for handling date time data.

library(lubridate)
x <- ymd("2018-10-31")
x + days(200)
[1] "2019-05-19"

lubridate works with 'period' objects, which require integers, so you would need to convert "4.3" months into something interpretable beforehand. "4.3" doesn't mean anything concrete in terms of date-time calculation anyways.

Upvotes: 1

Related Questions