Question

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.

Was it helpful?

Solution 3

Here's a way to do it with plyr (assuming, once again, that your data is in df):

library(plyr)
byDay = ddply(df, .(interval_id, indiv_id, role), transform, 
              day=seq(as.Date(start_date), as.Date(end_date), by=1))

The start_date and end_date values are repeated in every row, but you can just remove those if you wish.

OTHER TIPS

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

Old school (base) R:

new.dat <- do.call("rbind", as.list(by(dat, dat[,1:3], function(x) {

  return(data.frame(interval_id=x$interval_id, 
                    ndiv_id=x$indiv_id, 
                    role=x$role, 
                    day=seq(as.Date(x$start_date), as.Date(x$end_date), by=1)))

})))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top