Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201919

Difference between two dates in Months in R

$
0
0

I have a sample dataset as the one below:

df= data.frame("Finish_Date"=c("10/2019", "07/2005", "09/2008"), 
               "Recent_Date"="01/2020", stringsAsFactors = F)

I need to create a new column and calculate the difference between these two dates such that I get the difference in terms of "months". I have tried the solution from this post Get the difference between dates in terms of weeks, months, quarters, and years, however, I'm getting NA's in my result.

Below is the code that I have tried:

df$Due_Date=(as.yearmon(df$Recent_Date, format = "%Y-%m")-
                  as.yearmon(df$Finish_Date, format = "%Y-%m"))*12

My final output is supposed to be like:

| Finish_Date | Recent_Date | Due_Date |
|-------------|:-----------:|---------:|
| 10/2019     |   01/2020   |        3 |
| 07/2005     |   01/2020   |      174 |
| 09/2008     |   01/2020   |      136 |

Is there any way to get the result?


Viewing all articles
Browse latest Browse all 201919

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>