tags:

views:

68

answers:

2

I started using lubridate today. I have one variable called Started which is the date on which human sujbects enrolled in a study and another variable is called dos1 which is the date upon which the subject last had surgery. I want to work out how many months since their last surgery to the day of enrollment

as.period(syrrupan$Started-syrrupan$dos1,units=c("month"))

I was expecting this to give me something such as 14, 18, 1, 26 With each number being the number of months. Instead I get

1 year, -4 months, -5 days and -1 hours 1 year, -5 months, -23 days and -1 hours 1 year, -7 months, 2 days and -1 hours 1 year, -8 months, -28 days and 1 hour 1 year, -7 months, -23 days and 1 hour.
Furthermore my resultant vector does not wrap within the R console wedding. It just goes on forever to the right.

How do I fix it?

+1  A: 

You could try using difftime instead, ie:

difftime(syrrupan$Started,syrrupan$dos1,units="days")

Note that this will give you an object of class difftime, if you want a numeric vector, wrap an as.numeric around it. Note also that you can't choose months as an option for units, but you should really stick with a time unit that has a fixed length.

James
I read with interest the difference in Lubridate between an interval and a period and a duration. Yes, indeed, a month does not have a fixed length. However, for almost all but the most pedantic chronologist a month is equal to 365.25/12 = 30.44 days. I will try difftime later today and report back. Thanks for the suggestion.
Farrel
In that case you could just divide the above result by 30.44.
James
difftime is from the base package. Since the columns were "Date" I was also able to simply enter syrrupan$Started-syrrupan$dos1 which created a vector of class "difftime" in days. By the way, the syntax of difftime does not permit the minus sign, rather it should be just a comma. To get months and to have just one significant value after the decimal I used round(as.numeric(difftime(syrrupan$Started,syrrupan$dos1,units="days"))/30.44,1).
Farrel
difftime is from the base package. Since the columns were "Date" I was also able to simply enter syrrupan$Started-syrrupan$dos1 which created a vector of class "difftime" in days. By the way, the syntax of difftime does not permit the minus sign, rather it should be just a comma. To get months and to have just one significant value after the decimal I used round(as.numeric(difftime(syrrupan$Started,syrrupan$dos1,units="days"))/30.44,1). In lubridate I was able to do this round(as.numeric(as.duration(syrrupan$Started-syrrupan$dos1))/60/60/24/30.44,1) which seems clunky.
Farrel
Sorry, yes the minus sign crept in when I copied your variable names from the question. I've fixed the answer now.
James
+1  A: 

Hi Farrel,

That's definitely a bug in lubridate. I've made an error report and will fix it for version 0.1:

http://github.com/hadley/lubridate/issues#issue/75

Thanks for bringing it to my attention.

Garrett