Search code examples
rdatedifftime

Months difference function inconsistency


I have two vectors of dates. I need to find the difference in months between the two.

In a subset of the two vectors I have no problem.

However, as soon as I include the whole vector calculation stop making sense.

For example the difference between "2004-07-01" and "2004-09-30" stop being 3 and becomes 258490.

How do I find the couple of dates responsible of the issue?

Code

data_frames$dat1 <- as.Date(data_frames$dat1, format = "%Y-%m-%d")
data_frames$dat2 <- as.Date(data_frames$dat2, format = "%Y-%m-%d")

data_frames$months <- round(as.double(difftime(data_frames$dat1, data_frames$dat2))/365*12)  

View(data_frames)


Solution

  • Using mapply the problem does not emerge...

    dist_months <- function(x,y){
      round(as.double(difftime(as.Date(x,format = 
    "%Y-%m-%d"), as.Date(y, format = "%Y-%m-%d"))/365*12))
    }
    
    data_frames$months <- mapply(dist_months,data_frames$dat1,data_frames$dat2)