Switch to full style
Examples of R Scripting Language
Post a reply

Get Difference in days between two dates as a number

Tue Apr 04, 2017 9:01 pm

The following R script subtracts two dates and get the difference in days. The dates are in the String format. Thus, the R script has to use date format to convert the strings into dates.

Code:



diff
=as.Date(strptime("2004-02-03", "%Y-%m-%d"))-as.Date(strptime("2006-02-03", "%Y-%m-%d"))
diffNum=as.numeric(diff)
print(
diff);

 


This R script calculates the difference between two dates in the format of "year-month-day" (2004-02-03 and 2006-02-03) using the strptime() and as.Date() functions. The strptime() function is used to parse the date strings, and as.Date() is used to convert them to R's Date format. The difference between the two dates is then stored in the diff object. This difference is in the format of an object of class difftime, which represents elapsed time in units of days.
Then it converts the diff object to a numeric value and assigns it to diffNum variable. Finally, it prints the difference in days between the two dates.

This script calculates the difference in days between two dates, "2004-02-03" and "2006-02-03" using the strptime function to convert the dates from character strings to R date class and then subtract the two dates. The difference is then converted to a numeric format using the as.numeric() function and printed using the print() function.



Post a reply
  Related Posts  to : Get Difference in days between two dates as a number
 find the difference between dates in asp.net     -  
 Formatting dates in mysql     -  
 Comparing Dates in Java     -  
 DYNAMIC DATES IN MYSQL     -  
 convert integer number to octal,hexadecimal number systems     -  
 Validation of php drop down menu of months,days and years     -  
 convert octal number to decimal number     -  
 convert decimal number to octal number     -  
 difference between the >> and >>> operators     -  
 difference between the Boolean & operator and the &&     -  

Topic Tags

R Analysis