-2

I need to find the difference in days between 2 date columns, but one of them is in the format of "6/16/2019" and the other is in the format of "2019-02-25". Not sure which one would be easier to convert to which, but would like to get end result in days. Which I know how to do. I would appreciate help converting the second yyyy-mm-dd to mm-dd-yyyy.

Phil
  • 7,287
  • 3
  • 36
  • 66
Aamash
  • 1
  • 2
  • You could look into [lubridate](https://www.rdocumentation.org/packages/lubridate/versions/1.7.8). Dates are notoriously hard to deal with reliably, so using a standard package is usually better than rolling your own – John Coleman Apr 22 '20 at 02:31
  • 1
    Hi Aamash. This is in essence a duplicate of the linked posts. Take a look at the answers given there; it is trivial to adjust the solutions to give your desired output `mm-dd-yyyy`. If this doesn't work, I would recommend editing your post with details and code on *how* and *why* the solutions from the duplicate target posts do not work. – Maurits Evers Apr 22 '20 at 02:32

1 Answers1

0

We can use functions from the lubridate package to convert the different formats to dates, and then subtract.

rawData <- "date1,date2
2002-05-15,6/16/2019
2019-12-31,4/15/2020"

data <- read.csv(text = rawData,stringsAsFactors = FALSE)
library(lubridate)
mdy(data$date2) - ymd(data$date1) 

...and the output:

> mdy(data$date2) - ymd(data$date1) 
Time differences in days
[1] 6241  106
> 
Len Greski
  • 10,505
  • 2
  • 22
  • 33