英招

牢骚太盛防肠断,风物长宜放眼量

0%

计算时间序列年月日均值(by R)

前言:时间序列若存在时间缺漏与NA值,可选择补齐时间序列与插值,见时间序列补齐(by R)时间序列插值(by R)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#序列计算采用lubridate包,管道符采用dplyr包
library(lubridate)
library(dplyr)

#导入数据
data1<- read.table('E:\\data\\timeseries.txt',sep = "\t",encoding="UTF-8",header = T)
#将列名为time的列格式转化为时间格式(time形状类似“2020-10-01 01:00:00”)
data1$time<-as.POSIXct(data1$time)

#创造年列并求年均,列名为year
data1$year <- floor_date (data1$time, " year ")
#对列名为target的列求平均,保存在year变量中
year<-data1 %>%
group_by (year) %>%
summarize (mean_value = mean (target, na.rm = TRUE))

#创造月列并求月均,列名为month
data1$month <- floor_date (data1$time, " month ")
#对列名为target的列求平均,保存在month变量中
month<-data1 %>%
group_by (month) %>%
summarize (mean_value = mean (target, na.rm = TRUE))

#创造日列并求日均,列名为day
data1$day <- floor_date (data1$time, " day ")
#对列名为target的列求平均,保存在day变量中
month<-data1 %>%
group_by (day) %>%
summarize (mean_value = mean (target, na.rm = TRUE))

#导出
write.table(year,file="E:\\output\\年均.txt",sep = "\t",row.names=FALSE,col.names=TRUE)
write.table(month,file="E:\\output\\月均.txt",sep = "\t",row.names=FALSE,col.names=TRUE)
write.table(day,file="E:\\output\\日均.txt",sep = "\t",row.names=FALSE,col.names=TRUE)