在R中使用For with time series

时间:2016-06-27 20:14:08

标签: r for-loop zoo

例如,我有这个数据框名称DATA

Date        A 
22/02/2016  2
22/02/2016  6
23/02/2016  7
23/02/2016  9
24/02/2016  4
24/02/2016  8

首先我按天制作一个时间序列来创建一个新的数据框

require(zoo)
B <- as.POSIXct(strptime(DATA$Date, "%d/%m/%Y"))
Time_series <- seq.POSIXt(from=B[1],to=B[6],by="day")
DATA_2 <- data.frame(Time_series)

Time_series      
22/02/2016 
23/02/2016  
24/02/2016  

现在我想在每个日期输入变量A的平均值

A <- DATA$A

for (i in Time_series){
print(mean(A[which( B == i)]))
}

[1] 4
[1] 8
[1] 6

我的问题从这里开始,当我想制作打印值的矢量时。

想法是将向量添加到DATA_2

2 个答案:

答案 0 :(得分:1)

您可以使用此代码:

DATA_2$MEAN <-sapply(Time_series, function(x){
  mean(A[which( B == x)])
})

这是输出:

> DATA_2
  Time_series MEAN
1  2016-02-22    4
2  2016-02-23    8
3  2016-02-24    6

答案 1 :(得分:1)

require(zoo)
DATA <- data.frame(Date = seq(Sys.Date(),Sys.Date()+9,by=1), A=rnorm(10))

B <- as.POSIXct(strptime(DATA$Date, "%Y-%m-%d"))
Time_series <- seq.POSIXt(from=B[1],to=B[10],by="day")
DATA_2 <- data.frame(Time_series)

A <- aggregate(DATA,by=list(DATA$Date), mean)

DATA_2 <- cbind(DATA_2, A$A)
colnames(DATA_2) <- c("Date", "Mean of Response for this Date")
DATA_2

         Date Mean of Response for this Date
1  2016-06-27                    0.537861522
2  2016-06-28                   -0.872163819
3  2016-06-29                   -0.538401384
4  2016-06-30                    1.162449246
5  2016-07-01                   -1.490553854
6  2016-07-02                    0.220161925
7  2016-07-03                    0.057615735
8  2016-07-04                   -0.955184268
9  2016-07-05                    0.007144786
10 2016-07-06                   -0.157812297