【问题标题】:week day week-percent from time-seriesweek day week-percent from time-series
【发布时间】:2012-11-18 18:18:30
【问题描述】:

我有一些每日时间序列数据,我需要提取相对于一周平均值的“工作日百分比”。例如,如果第一周有 mean = 100 并且本周的 Sunday 值为 20,则 sunday 变为 0.2。

这是一些随机数据:

set.seed(0)
y = rnorm(1705)
date = seq(as.Date('2008-01-01'), by = 'day', length = length(y))
data.df = data.frame(y, date)

我需要一个名为pecent 的新列,即上面解释的值。我尝试添加一些 然后列使用tapply,但失败了。感谢任何帮助!

【问题讨论】:

    标签: r time-series tapply


    【解决方案1】:

    首先使用format 创建一个week 变量。然后使用ddplytransform

    library(plyr)
    data.df$week <- format(data.df$date,'%W %Y') #week begins with Monday
    data.df <- ddply(data.df,~week,transform,percent=y/mean(y))
    head(data.df)
    
               y       date    week    percent
    1  1.2629543 2008-01-01 00 2008  3.1395415
    2 -0.3262334 2008-01-02 00 2008 -0.8109741
    3  1.3297993 2008-01-03 00 2008  3.3057095
    4  1.2724293 2008-01-04 00 2008  3.1630952
    5  0.4146414 2008-01-05 00 2008  1.0307451
    6 -1.5399500 2008-01-06 00 2008 -3.8281172
    

    请注意,第 00 周通常不像一年中的最后一周那样是一整周。如果重要的话,合并随后几年的最后几周和第一周。

    【讨论】:

    • 为避免每年年初和年末的周数不完整,您可以使用一周的第一天来标识周,而不是周号:date - as.numeric(format(date,"%u")) + 1
    • 谢谢,正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2013-12-13
    • 2011-04-09
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多