# Getting the number of weeks from a time span [closed]

I have a very big clinical data like

Date.Death  Date Of Operation
02/08/2015  27/11/2012
02/08/2015  27/11/2012


I want to know how many weeks each patient has lived after operation

I then tried

> t1 <- as.POSIXct("27/11/2012")
> t2 <- as.POSIXct("02/08/2015")
> as.double(difftime(t2,t1,unit="weeks"))
[1] -1317.571


Or

> span <- interval(as.POSIXct("27/11/2012"), as.POSIXct("02/08/2015"))
> span
[1] 0027-11-20 LMT--0002-08-20 LMT
> t <- as.period(span, unit="day")
> t
[1] "-9223d 0H 0M 0S"
> t / as.period(dweeks(1))
estimate only: convert to intervals for accuracy
[1] -1317.571


Both give wrong number of weeks

Manually calculating one by one is painful and error prone

You know anyway to get the number of weeks?

Thanks

• I'm voting to close this question as off-topic because it has nothing to do with bioinformatics.
– terdon
Commented Apr 6, 2020 at 9:46
• statmethods.net/input/dates.html Commented Apr 6, 2020 at 14:53

## 1 Answer

I think your error is located in your use of as.POSIXct which gives you wrong date formats because you did not provide a format in your function:

> as.POSIXct("27/11/2012")
[1] "27-11-20 LMT"

> as.POSIXct("27/11/2012", format = "%d/%m/%Y")
[1] "2012-11-27 PST"


So, you need to first convert your date in the appropriate date format and then you will be able to calculate the time interval.

Personally, I prefer to manipulate dates with lubridate package because the name of their function is a little bit more intuitive to me. For example, if you have a date to the format "Day/Month/Year", you can use dmy function.

With your example, you can do:

library(lubridate)
library(dplyr)

df <- data.frame(Date.Death = c("02/08/2015","02/05/2015"),
Date.Operation = c("27/11/2012","27/11/2012"))

df %>% mutate_all(~dmy(.)) %>%
mutate(Diff_Weeks = interval(Date.Operation,Date.Death) / weeks(1),
Diff_days = Date.Death - Date.Operation)

Date.Death Date.Operation Diff_Weeks Diff_days
1 2015-08-02     2012-11-27   139.7143  978 days
2 2015-05-02     2012-11-27   126.5714  886 days
$$$$
`
• Sorry why inviting me? :( I googled a lot but I did not find the solution Commented Apr 5, 2020 at 14:42