lubridate
Convert dd/mm/yy and dd/mm/yyyy to Dates
You can use parse_date_time from lubridate: some.dates <- c(“23/11/12”, “20/10/2012”, “22/10/2012″ ,”23/11/12”) parse_date_time(some.dates,c(‘dmy’)) [1] “2012-11-23 UTC” “2012-10-20 UTC” “2012-10-22 UTC” “2012-11-23 UTC” But , Note that the order of format is important : some.dates <- c(“20/10/2012″,”23/11/12”, “22/10/2012″ ,”23/11/12”) parse_date_time(some.dates,c(‘dmY’,’dmy’)) [1] “2012-10-20 UTC” “2012-11-23 UTC” “2012-10-22 UTC” “2012-11-23 UTC” EDIT Internally parse_date_time is using guess_formats (which … Read more
Is there a more elegant way to convert two-digit years to four-digit years with lubridate?
Here is a function that allows you to do this: library(lubridate) x <- mdy(c(“1/2/54″,”1/2/68″,”1/2/69″,”1/2/99″,”1/2/04”)) foo <- function(x, year=1968){ m <- year(x) %% 100 year(x) <- ifelse(m > year %% 100, 1900+m, 2000+m) x } Try it out: x [1] “2054-01-02 UTC” “2068-01-02 UTC” “1969-01-02 UTC” “1999-01-02 UTC” [5] “2004-01-02 UTC” foo(x) [1] “2054-01-02 UTC” “2068-01-02 … Read more
Generate a sequence of the last day of the month over two years
Yes, you found the correct trick: going back a day from the first of the next month. Here is as a one-liner in base R: R> seq(as.Date(“2010-02-01″), length=24, by=”1 month”) – 1 [1] “2010-01-31” “2010-02-28” “2010-03-31” “2010-04-30” “2010-05-31” [6] “2010-06-30” “2010-07-31” “2010-08-31” “2010-09-30” “2010-10-31” [11] “2010-11-30” “2010-12-31” “2011-01-31” “2011-02-28” “2011-03-31” [16] “2011-04-30” “2011-05-31” “2011-06-30” “2011-07-31” … Read more
How to flatten / merge overlapping time periods
Here’s a possible solution. The basic idea here is to compare lagged start date with the maximum end date “until now” using the cummax function and create an index that will separate the data into groups data %>% arrange(ID, start) %>% # as suggested by @Jonno in case the data is unsorted group_by(ID) %>% mutate(indx … Read more