Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand time interval data into days in R

Tags:

r

time-series

Suppose I have data that looks like this:

interval_id indiv_id   role start_date   end_date
          1        1      A 2006-05-01 2006-06-16
          2        1      B 2006-06-16 2006-10-16
          3        1      A 2006-10-16 2009-10-16
          4        1      B 2009-10-16 2014-04-23
          5        2      A 2007-12-15 2009-10-16
          6        2      B 2009-10-16 2011-07-01

But I want data that looks like this (taking the first role interval as an example):

interval_id indiv_id   role        day
          1        1      A 2006-05-01
          1        1      A 2006-05-02
          1        1      A 2006-05-03
          1        1      A 2006-05-04
          1        1      A 2006-05-05
          1        1      A 2006-05-06
        ...      ...    ...        ...
          1        1      A 2006-06-16

I'm doing this with a loop in R. Pretty sure that is unnecessary. Is there a package for expanding time intervals like this? Seems like a reshape-type job since I'm kind of turning a time interval into a long format data set.

Thanks.

like image 855
Brash Equilibrium Avatar asked Dec 19 '22 15:12

Brash Equilibrium


1 Answers

Here's a way with data tables (assumes your data is in df).

library(data.table)
dt <- data.table(df)
dt <- dt[,seq(as.Date(start_date),as.Date(end_date),by=1),
          by=list(interval_id,indiv_id,role)]
setnames(dt,"V1","day")
head(dt)
#    interval_id indiv_id role        day
# 1:           1        1    A 2006-05-01
# 2:           1        1    A 2006-05-02
# 3:           1        1    A 2006-05-03
# 4:           1        1    A 2006-05-04
# 5:           1        1    A 2006-05-05
# 6:           1        1    A 2006-05-06
like image 87
jlhoward Avatar answered Dec 28 '22 07:12

jlhoward