首页 文章

使用lubridate按月迭代并合并

提问于
浏览
0

我正在尝试编写一个函数,该函数基于两个数据帧中的两列进行合并 . 其中一列是标识符字符串,另一列是日期 .

第一个df(“模型”)包括标识符,开始日期和一些其他相关信息 .

第二个df(“futurevalues”)是一个融合的df,包括标识符,每个标识符的多个月,以及每个标识符 - 月对的相关值 .

我想根据将来某段时间合并每个标识符的值 . 因此,例如,对于Identifier = Mary和“model”中的起始月份=“2005-01-31”,我想提取下个月的相关值以及之后的11个月(因此,Mary的数据点为12个月)从第1个月开始:从12月开始) .

我可以通过两列合并我的dfs来获取as-of date值(见下文),但这不是我需要的 .

testmerge=merge(model,futurevalues,by=c("month","identifier"),all=TRUE)

为了解决这个问题,我试图使用lubridate日期函数 . 例如,下面的函数将允许我输入一个月(然后在df中翻译)以获得每个起始月份的值(在整个df中变化,这意味着它不是整个事物的标准时间段) ) .

monthiterate=function (x) {
 x %m+% months(1:12) 
}

非常感谢你的帮助 .

编辑:添加玩具数据(第一个是模型,第二个是未来值)

structure(list(month = structure(c(12814, 12814, 12814, 12814, 
12814, 12814, 12814, 12814, 12814, 12814), class = "Date"), identifier = structure(c(1L, 
3L, 2L, 4L, 5L, 7L, 8L, 6L, 9L, 10L), .Label = c("AB1", "AC5", 
"BB9", "C99", "D81", "GG8", "Q11", "R45", "ZA1", "ZZ9"), class = "factor"), 
value = c(0.831876072999969, 0.218494398256579, 0.550872926656984, 
1.81882711231324, -0.245597705276932, -0.964277509916354, 
-1.84714556574606, -0.916239506529079, -0.475649743547525, 
-0.227721186387637)), .Names = c("month", "identifier", "value"
 ), class = "data.frame", row.names = c(NA, 10L))

 structure(list(identifier = structure(c(1L, 3L, 2L, 4L, 5L, 7L, 
 8L, 6L, 9L, 10L), .Label = c("AB1", "AC5", "BB9", "C99", "D81", 
 "GG8", "Q11", "R45", "ZA1", "ZZ9"), class = "factor"), month = structure(c(12814, 
 13238, 12814, 12814, 12964, 12903, 12903, 12842, 13148, 13148
 ), class = "Date"), futurereturns = c(-0.503033205660682, 1.22446988772542, 
 -0.825490985851348, 1.03902417581908, 0.172595565260429, 0.894967582911769, 
 -0.242324006922964, 0.415520398113024, -0.734437328639625, 2.64184935856802
 )), .Names = c("identifier", "month", "futurereturns"), class = "data.frame", row.names      
 = c(NA, 10L))

1 回答

  • 2

    您需要创建一个包含所需ID和月份组合的表 . 从每个ID及其起始月份的表开始:

    library(lubridate)
    set.seed(1834)
    # 3 people, each with a different starting month
    x <- data.frame(id = sample(LETTERS, 3)
                    , month = ymd("2005-01-01") + months(sample(0:11, 3)) - days(1))
    
    > x
      id      month
    1  D 2005-03-31
    2  R 2005-07-31
    3  Y 2005-02-28
    

    现在为每个ID添加以下两个月的行 . 我使用 dplyr 来做这种事情 .

    library(dplyr)
    y <- x %>%
      rowwise %>%
      do(data.frame(id = .$id
                    , month = seq(.$month + days(1)
                                  , by = "1 month"
                                  , length.out = 3) - days(1)))
    
    > y
    Source: local data frame [9 x 2]
    Groups: <by row>
    
      id      month
    1  D 2005-03-31
    2  D 2005-04-30
    3  D 2005-05-31
    4  R 2005-07-31
    5  R 2005-08-31
    6  R 2005-09-30
    7  Y 2005-02-28
    8  Y 2005-03-31
    9  Y 2005-04-30
    

    现在,您可以使用 merge() (或 dplyr 中的 left_join() )从完整数据集中检索所需的行 .

相关问题