在 R 中将时间间隔数据扩展为天 [英] Expand time interval data into days in R

查看:21
本文介绍了在 R 中将时间间隔数据扩展为天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下所示的数据:

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

我正在用 R 中的循环来做这件事.很确定这是不必要的.有没有扩展这样的时间间隔的包?似乎是一种重塑型工作,因为我正在将时间间隔转换为长格式数据集.

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.

谢谢.

推荐答案

这里有一种方法可以使用 plyr(再次假设您的数据在 df>):

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))

start_date 和 end_date 值在每一行中重复,但您可以根据需要删除它们.

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

这篇关于在 R 中将时间间隔数据扩展为天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆