bvowe
bvowe

Reputation: 3384

Subtract month/year to get years

data = data.frame("start"= c("1/2000","8/2004","99/9999"),
                  "stop"=c("1/2001","2/2007","09/2010"),
                  "WANTYEARS"= c(1,2.5,NA))

I have date in month/year format and want to subtract to get the years.

My attempt of simple data$stop - data$start did not yield the desired results. THank you.

Upvotes: 2

Views: 96

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269586

The yearmon class represents months and years as years and fraction of a year.
Using data shown in the Note at the end:

library(zoo)

transform(data, diff = as.yearmon(stop, "%m/%Y") - as.yearmon(start, "%m/%Y"))

giving:

    start    stop diff
1  1/2000  1/2001  1.0
2  8/2004  2/2007  2.5
3 99/9999 09/2010   NA

Note

data = data.frame(start= c("1/2000", "8/2004", "99/9999"),
                  stop = c("1/2001", "2/2007", "09/2010"))

Upvotes: 2

tmfmnk
tmfmnk

Reputation: 39858

One possibility involving dplyr and lubridate could be:

data %>%
 mutate_at(vars(1:2), list(~ parse_date_time(., "my"))) %>%
 mutate(WANTYEARS =  round(time_length(stop - start, "years"), 1))

       start       stop WANTYEARS
1 2000-01-01 2001-01-01       1.0
2 2004-08-01 2007-02-01       2.5
3       <NA> 2010-09-01        NA

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

One option is to use difftime from base R. Add "01" to stop and start date to create an actual Date object and subtract those dates using difftime with unit as "weeks" and divide it by number of weeks in year to get time difference in year,

round(difftime(as.Date(paste0("01/", data$stop), "%d/%m/%Y"), 
      as.Date(paste0("01/", data$start), "%d/%m/%Y"), units = "weeks")/52.2857, 2)

#[1] 1.0 2.5  NA

We can do the same using any other unit component of difftime as well if we know the equivalent year conversion ratio like for example with "days"

round(difftime(as.Date(paste0("01/", data$stop), "%d/%m/%Y"), 
      as.Date(paste0("01/", data$start), "%d/%m/%Y"), units = "days")/365.25, 2)
#[1] 1.0 2.5  NA

Upvotes: 1

Related Questions