根据R中缺失数据的时间序列计算周平均值
我有一个时间序列对象,它的每日值始于19世纪,一直延续到20世纪。其中有许多缺少的值 我试图计算每周平均值,这里有一个最小的例子:根据R中缺失数据的时间序列计算周平均值,r,dataframe,time-series,xts,missing-data,R,Dataframe,Time Series,Xts,Missing Data,我有一个时间序列对象,它的每日值始于19世纪,一直延续到20世纪。其中有许多缺少的值 我试图计算每周平均值,这里有一个最小的例子: library(zoo) library(xts) # Create time series that starts in 19th century T <- 100 # number of days myTS <- xts(rnorm(T), as.Date(1:T, origin="1899-11-05")) # Insert some miss
library(zoo)
library(xts)
# Create time series that starts in 19th century
T <- 100 # number of days
myTS <- xts(rnorm(T), as.Date(1:T, origin="1899-11-05"))
# Insert some missing values
myTS[4:7] <- NA
myTS[33:34] <- NA
myTS[67:87] <- NA
# Try calculating weekly means
weekData <- apply.weekly(myTS, colMeans, na.rm = TRUE)
图书馆(动物园)
图书馆(xts)
#创建始于19世纪的时间序列
T根据您的评论更新使用周-年组合:
library(zoo)
library(xts)
# Create time series that starts in 19th century
T <- 100 # number of days
myTS <- xts(rnorm(T), as.Date(1:T, origin="1899-11-05"))
# Insert some missing values
myTS[4:7] <- NA
myTS[33:34] <- NA
myTS[67:87] <- NA
# Let's use a flexible class
myTS <- data.frame(dates=index(myTS),v1=myTS[,1])
# Here's an easy way to transform dates to weeks
require(lubridate)
week_num <- week(myTS[,1])
year_num <- year(myTS[,1])
week_yr <- paste(week_num, year_num)
# Weekly means
aggregate(myTS$v1,by=list(week_yr),mean,na.rm=T)
对不起,我想要的不是跨年1周、跨年2周等的平均值。但我想分别计算这几周的平均值。所以,1899年1月1日,1899年2月2日,…,1900年52月5日,1900年53月5日。太棒了,完成任务了!
Group.1 x
1 1 1900 0.05405322
2 2 1900 0.31981319
3 3 1900 NaN
4 4 1900 NaN
5 45 1899 0.85081053
6 46 1899 0.34064255
7 47 1899 0.02880424
8 48 1899 -0.34408119
9 49 1899 -0.38089026
10 5 1900 0.62292188
11 50 1899 -0.59666955
12 51 1899 0.57756987
13 52 1899 -0.41325485
14 53 1899 0.88013634
15 6 1900 0.01514668
16 7 1900 -0.50863942