Search code examples
rdatesubtraction

How to calculate difference between dates in R


I am working on a project right now and encountered this problem.

I have a dataset consisting of two dates columns. One, say it x1, stands for check-in dates, the other, say it x2, stands for check-out dates.

Both of them are in the "year-month-day" format and have the type of string.

What I would like to do is figuring out how long does a person stay using check-in, check-out dates. I've tried multiple functions like as.Date. But all failed and I believe I just can't subtract these two dates directly as the results wouldn't represent the actual stay length.

Does anybody have any idea on how to do this in R?

Thanks!


Solution

  • If I understood your question, you want the difference between checkout and checkin? I would try this:

    library(lubridate)
    df<-data.frame(x1=c("2017-03-23","2017-03-24"),x2=c("2017-03-24","2017-03-28"))
    df[]<-lapply(df,ymd)
    df$x2-df$x1