子集列按月的最后一个数据

时间:2016-06-24 00:49:16

标签: r

我认为这是一个简单的问题。但我在数据框的子集中遇到问题。

这是我的data.frame:

df<-Forward[,-c(1:2)]
head(df,100)
                   NA.   GBP_1M
        1   1988-12-29 1.785200
        2   1988-12-30 1.802700
        3   1989-01-04 1.800100
        4   1989-01-10 1.757200
        5   1989-01-16 1.754000
        6   1989-01-17 1.765500
        7   1989-01-24 1.763500
        8   1989-01-25 1.765200
        9   1989-01-27 1.753100
        10  1989-01-31 1.747900
        11  1989-02-02 1.741900
        12  1989-02-03 1.737900
        13  1989-02-08 1.739899
        14  1989-02-17 1.773599
        15  1989-02-23 1.757700
        16  1989-02-24 1.749800
        17  1989-02-27 1.734000
        18  1989-02-28 1.739101
        19  1989-03-01 1.718601
        20  1989-03-02 1.708300
        21  1989-03-03 1.717000
        22  1989-03-06 1.718701
        23  1989-03-07 1.716400
        24  1989-03-08 1.710900
        25  1989-03-09 1.718000
        26  1989-03-10 1.715999
        27  1989-03-13 1.708800
        28  1989-03-14 1.724499
        29  1989-03-15 1.715000
        30  1989-03-16 1.716900
        31  1989-03-17 1.709700
        32  1989-03-20 1.715600
        33  1989-03-21 1.721400
        34  1989-03-22 1.724400
        35  1989-03-23 1.716800
        ...
        98  1989-06-23 1.561200
        99  1989-06-26 1.542599
        100 1989-06-27 1.557500

我想创建第三列,其中包含每个NA.个月的最后一个值。

当我使用:setDT(df)[, last := tail(GBP_1M,1), .(month(NA.))]时, 它没有给我每个月的最后价值:

在第一行中给我:1,8027,第二行1.747900等等......

        NA.     GBP_1M     last
 1: 1988-12-29 1.785200 1.473520
 2: 1988-12-30 1.802700 1.473520
 3: 1989-01-04 1.800100 1.424445
 4: 1989-01-10 1.757200 1.424445
 5: 1989-01-16 1.754000 1.424445
 6: 1989-01-17 1.765500 1.424445
 7: 1989-01-24 1.763500 1.424445
 8: 1989-01-25 1.765200 1.424445
 9: 1989-01-27 1.753100 1.424445
10: 1989-01-31 1.747900 1.424445
11: 1989-02-02 1.741900 1.391475
12: 1989-02-03 1.737900 1.391475
13: 1989-02-08 1.739899 1.391475
14: 1989-02-17 1.773599 1.391475
15: 1989-02-23 1.757700 1.391475
16: 1989-02-24 1.749800 1.391475
17: 1989-02-27 1.734000 1.391475
18: 1989-02-28 1.739101 1.391475
19: 1989-03-01 1.718601 1.439525

非常感谢。

1 个答案:

答案 0 :(得分:0)

我们可以使用base R

执行此操作
df$last <- with(df, ave(GBP_1M, format(NA., "%Y"), format(NA., "%M"), 
                                  FUN = function(x) tail(x, 1)))