y_100 <- Sys.Date() - (100 * 365.25) + -1:1
diff_dates(y_100)
# with "to_date" argument:
y_050 <- Sys.Date() - (50 * 365.25) + -1:1
diff_dates(y_100, y_050)
diff_dates(y_100, y_050, unit = "d") # days (with decimals)
# Time unit and output format:
ds_from <- as.Date("2010-01-01") + 0:2
ds_to <- as.Date("2020-03-01") # (2020 is leap year)
diff_dates(ds_from, ds_to, unit = "y", as_character = FALSE) # years
diff_dates(ds_from, ds_to, unit = "m", as_character = FALSE) # months
diff_dates(ds_from, ds_to, unit = "d", as_character = FALSE) # days
# Robustness:
days_cur_year <- 365 + is_leap_year(Sys.Date())
diff_dates(Sys.time() - (1 * (60 * 60 * 24) * days_cur_year)) # for POSIXt times
diff_dates("10-08-11", "20-08-10") # for strings
diff_dates(20200228, 20200301) # for numbers (2020 is leap year)
# Recycling "to_date" to length of "from_date":
y_050_2 <- Sys.Date() - (50 * 365.25)
diff_dates(y_100, y_050_2)
# Note maxima and minima:
diff_dates("0000-01-01", "9999-12-31") # max. d + m + y
diff_dates("1000-06-01", "1000-06-01") # min. d + m + y
# If from_date == to_date:
diff_dates("2000-01-01", "2000-01-01")
# If from_date > to_date:
diff_dates("2000-01-02", "2000-01-01") # Note negation "-"
diff_dates("2000-02-01", "2000-01-01", as_character = TRUE)
diff_dates("2001-02-02", "2000-02-02", as_character = FALSE)
# Test random date samples:
f_d <- sample_date(size = 10)
t_d <- sample_date(size = 10)
diff_dates(f_d, t_d, as_character = TRUE)
# Using 'fame' data:
dob <- as.Date(fame$DOB, format = "%B %d, %Y")
dod <- as.Date(fame$DOD, format = "%B %d, %Y")
head(diff_dates(dob, dod)) # Note: Deceased people do not age further.
head(diff_dates(dob, dod, as_character = FALSE)) # numeric outputs
Run the code above in your browser using DataLab