R 时间序列中的周-日-周百分比
我有一些每日时间序列数据,我需要提取相对于周平均值的“周-日百分比”。例如,如果第一周的平均值为100,而本周的星期日值为20,则星期日变为0.2 以下是一些随机数据:R 时间序列中的周-日-周百分比,r,time-series,tapply,R,Time Series,Tapply,我有一些每日时间序列数据,我需要提取相对于周平均值的“周-日百分比”。例如,如果第一周的平均值为100,而本周的星期日值为20,则星期日变为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的新列,它是上面解释的值。我试着添加一些 列然后使用t
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
,但失败。谢谢你的帮助 首先使用格式
创建一个周
变量。然后使用ddply
和transform
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
库(plyr)
data.df$week首先使用格式创建week
变量。然后使用ddply
和transform
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
库(plyr)
data.df$week为了避免在每年的开始和结束时出现不完整的周,您可以使用周的第一天来标识周,而不是周号:date-as.numeric(格式(日期,“%u”))+1
。谢谢,这正是我需要的!为了避免在每年的开始和结束时出现不完整的周,您可以使用周的第一天来标识周,而不是周号:date-as.numeric(format(date,“%u”)+1
。谢谢,这正是我需要的!