0

So I need to create a function that take a number of dates, n, and creates a new vector with date ranges, n-1, and the different in number of days between those dates ranges.

c("Jan. 20, 2009", "July 20, 1969", "June 28, 1914", "July 14, 1789", "Oct. 
14, 1066"))
Time differences in days
10/14/1066-7/14/1789  7/14/1789-6/28/1914  6/28/1914-7/20/1969 
          263979                45638                20111 
7/20/1969-1/20/2009 
           14429

This is what I have so far. I'm struggling to find a way to iterate and create a shorter vector. I already reformatted the dates, but I can't figure out how to concatenate the dates in ranges and get the counts of the days in those date ranges. I'm trying class(d) below in the code but it's not working.

days_between = function(v) {
    sort(mdy(v))
    d = ymd("1066-10-14") - ymd("1789-07-14") 
    class(d)
}

Hopefully this is specific enough and makes sense. Thanks.

stevie kay
  • 53
  • 1
  • 6
  • Please do not provide your test data as an image. No one wants to type it all in again. – G5W Mar 16 '18 at 15:14
  • Also, please clarify your desired outputs. It sounds like you want 3 outputs: (1) "date ranges" (what do you mean by this? the start and end days? In what format?) (2) "n-1" (do you just want it to print the number one less than the length of the input?) (3) number of days between those ranges (You seem to be sorting - do you want the differences between consecutive sorted dates? Between all pairs of dates? Between dates in the order entered?) – Gregor Thomas Mar 16 '18 at 15:17
  • @G5W Changed it. – stevie kay Mar 16 '18 at 15:35
  • @Gregor Desired output is everything below "time differences" in the code above that i changed from picture to code. – stevie kay Mar 16 '18 at 15:36
  • @Gregor the names in the time difference in days is the same. It should have the next closest day on the right side of each "-" in each column name – stevie kay Mar 16 '18 at 16:21
  • @Gregor it's also excluding 10/14/1066 in the beginning column – stevie kay Mar 16 '18 at 16:22

1 Answers1

1
    x = c("Jan. 20, 2009", "July 20, 1969", "June 28, 1914", "July 14, 1789", "Oct. 
    14, 1066")

    d = lubridate::mdy(x)
    d = d[order(d)]
    result = diff(d)
    labels = format(d, "%m/%d/%Y")
    names(result) = paste(head(labels, -1), labels[-1], sep = "-")
    result
    Time differences in days
    # 10/14/1066-07/14/1789 07/14/1789-06/28/1914 06/28/1914-07/20/1969 07/20/1969-01/20/2009 
    #                263979                 45638                 20111                 14429 
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294