将两个日期之间的行生成到R中的数据框中 [英] Generate rows between two dates into a data frame in R

查看:59
本文介绍了将两个日期之间的行生成到R中的数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习R很短的时间。我有下表

I've just started learning R for a short time. I have the following table

Name      stDte      edDte  
A    2010-05-01 2014-12-01  
B    2013-06-01 2014-02-01  

我需要将其转换为表格像这样

I need to get it transformed into a table like this

Name   Dte
A      2010-05-01
A      2010-06-01
A      2010-07-01
...
A      2014-12-01
B      2013-06-01
B      2013-07-01
...
B      2014-02-01

我正在考虑结合使用与rbind一起使用的 for循环,但是我不确定该怎么做。将不胜感激有关如何做到这一点的任何建议。在此先感谢您的指导

I'm thinking about using a combination of a 'for' loop for together with rbind but I'm not sure how to go about it. Would appreciate any suggestions on how to do that. Thanks in advance for the guidance

推荐答案

由于您没有另外说明,因此此答案假定 stDte edDte 列都是 Date类。

Since you don't state otherwise, this answer assumes the stDte and edDte columns are both of "Date" class.

在R基中可以使用 Map()创建日期序列,然后使用 data.frame 将新数据框放在一起使用 rep.int()创建新的 Name 列。

In base R you could use Map() to create the sequence of dates, then data.frame to bring the new data frame together after creating the new Name column with rep.int().

M <- Map(seq, df$stDte, df$edDte, by = "month")
df2 <- data.frame(
    Name = rep.int(df$Name, vapply(M, length, 1L)), 
    Dte = do.call(c, M)
)    
str(df2)
# 'data.frame':    65 obs. of  2 variables:
#  $ Name: Factor w/ 2 levels "A","B": 1 1 1 1 1 1 1 1 1 1 ...
#  $ Dte : Date, format: "2010-05-01" "2010-06-01" ...
head(df2, 3)
#   Name        Dte
# 1    A 2010-05-01
# 2    A 2010-06-01
# 3    A 2010-07-01
tail(df2, 3)
#    Name        Dte
# 63    B 2013-12-01
# 64    B 2014-01-01
# 65    B 2014-02-01

或者您可以使用 data.table 包并执行

Or you can use the data.table package and do

library(data.table)
setDT(df)[, .(Dte = seq(stDte, edDte, by = "month")), by = Name]

这篇关于将两个日期之间的行生成到R中的数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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