hermesh2
10/4/2015 - 2:31 PM

substract dates.R

library(data.table)
library(dplyr)
########################################################################################
# Create example data set
########################################################################################
set.seed(123456)
data <- data.frame( id = 1:100,
                    Date1 =  Sys.Date( ) + sample( -1000: 1000, 100)  ,
                    Date2 = as.character( Sys.Date( ) + sample( -1000: 1000, 100) ) ,
                    Date3 = Sys.Date( ) + sample( -1000: 1000, 100) 
)

########################################################################################
# Function
########################################################################################
DiffDates <-
  function( data, DTNames = NULL, format = "%Y-%m-%d", DateForDifference = Sys.Date(), ...  ){
    # data with detes to compute the difference
    # Names of dates colums if the colums has date format ignore this
    # format of the dates if is DTnNames = NULL ignore this parameter
    # Date for compute the difference
    
    if( !is.data.table( data ) ){
      data <-  data.table( data)
      warning( "Warning: Be carrefull data frame or matrix transformed to data table")
    }
    
    print( class( data))
    
    if( is.null( DTNames ) ){
      DTNames <- names(data)[ sapply(X =  data , FUN = class) == "Date" ]
    }else{ # Otherwise transform to date some colums
      # transform DT in to Date class. For more info about data.table lapply see: 
      # http://stackoverflow.com/questions/9236438/how-do-i-run-apply-on-a-data-table
      data[ , (DTNames) := 
              lapply(X = .SD,
                     FUN = function(x, format){
                       as.Date( x, format)
                     }),
            .SDcol = DTNames]
    }
    print( class( data))
    data[ , (DTNames) :=
            lapply(X = .SD,
                   FUN = function(x, format){
                     difftime( time1 = x, time2 =   DateForDifference, ...) # Dots allows to call others parameters of this function in the main one
                   }),
          .SDcol = DTNames]
    
  }
summary(data) # show the original data set

########################################################################################
# Example 1
########################################################################################
DiffDates(data = data, units = "days") 

########################################################################################
# Example 2
########################################################################################
data$Date2 <- data$Date2 %>% as.Date(format = "%Y-%m-%d") 
DiffDates(data = data, DTNames =c("Date1", "Date2" , "Date3"), units = "days")