将两个日期之间的行生成到 R 中的数据框中 [英] Generate rows between two dates into a data frame in 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
我正在考虑将for"循环与 rbind 结合使用,但我不知道该怎么做.将不胜感激有关如何做到这一点的任何建议.提前感谢您的指导
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
列都是日期"类.
Since you don't state otherwise, this answer assumes the stDte
and edDte
columns are both of "Date" class.
在基础 R 中,您可以使用 Map()
创建日期序列,然后在创建新 后使用
列与 data.frame
将新数据框组合在一起>Namerep.int()
.
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屋!