简体   繁体   English

如何在 R 中对时间序列进行子集化

[英]How to subset a time series in R

In particular, I'd like to subset the temperature measurements from 1960 onwards in the time series gtemp in the package astsa :特别是,我想在gtemp包中的时间序列gtemp中对1960年以后的温度测量值进行子集astsa

在此处输入图片说明

require(astsa)
gtemp
Time Series:
Start = 1880 
End = 2009 
Frequency = 1 
  [1] -0.28 -0.21 -0.26 -0.27 -0.32 -0.32 -0.29 -0.36 -0.27 -0.17 -0.39 -0.27 -0.32
 [14] -0.33 -0.33 -0.25 -0.14 -0.11 -0.25 -0.15 -0.07 -0.14 -0.24 -0.30 -0.34 -0.24
 [27] -0.19 -0.39 -0.33 -0.35 -0.33 -0.34 -0.32 -0.30 -0.15 -0.10 -0.30 -0.39 -0.33
 [40] -0.20 -0.19 -0.14 -0.26 -0.22 -0.22 -0.17 -0.02 -0.15 -0.12 -0.26 -0.08 -0.02
 [53] -0.08 -0.19 -0.07 -0.12 -0.05  0.07  0.10  0.01  0.04  0.10  0.03  0.09  0.19
 [66]  0.06 -0.05  0.00 -0.04 -0.07 -0.16 -0.04  0.03  0.11 -0.10 -0.10 -0.17  0.08
 [79]  0.08  0.06 -0.01  0.07  0.04  0.08 -0.21 -0.11 -0.03 -0.01 -0.04  0.08  0.03
 [92] -0.10  0.00  0.14 -0.08 -0.05 -0.16  0.12  0.01  0.08  0.18  0.26  0.04  0.26
[105]  0.09  0.05  0.12  0.26  0.31  0.19  0.37  0.35  0.12  0.13  0.23  0.37  0.29
[118]  0.39  0.56  0.32  0.33  0.48  0.56  0.55  0.48  0.62  0.54  0.57  0.43  0.57

The individual time points are not labeled in years, so although I can do gtemp[3] [1] -0.26 , I can't do gtemp[as.date(1960)] , for instance to get the value in 1960.各个时间点没有以年为单位标记,因此虽然我可以执行gtemp[3] [1] -0.26 ,但我不能执行gtemp[as.date(1960)] ,例如获取 1960 年的值。

How can I bring out the correspondence between year and measurements, so as to later subset values?我怎样才能带出年份和测量值之间的对应关系,以便以后的子集值?

We can make use of the window function我们可以利用window函数

gtemp1 <- window(gtemp, start = 1960)
gtemp1
#Time Series:
#Start = 1960 
#End = 2009 
#Frequency = 1 
#[1] -0.01  0.07  0.04  0.08 -0.21 -0.11 -0.03 -0.01 -0.04  0.08  0.03
#[12]-0.10  0.00  0.14 -0.08 -0.05 -0.16  0.12  0.01  0.08  0.18  0.26  
#[23] 0.04  0.26  0.09  0.05   0.12  0.26  0.31  0.19  0.37  0.35  0.12
#[34] 0.13  0.23  0.37  0.29  0.39  0.56  0.32  0.33  0.48  0.56  0.55
#[45] 0.48  0.62  0.54  0.57  0.43  0.57

Function time can also help to answer your question功能time也可以帮助回答您的问题

How can I bring out the correspondence between year and measurements, so as to later subset values?我怎样才能带出年份和测量值之间的对应关系,以便以后的子集值?

head(time(gtemp))
[1] 1880 1881 1882 1883 1884 1885

If you want the value that corresponds to 1961, you can write如果你想要1961对应的值,你可以写

gtemp[time(gtemp) == 1961]
[1] 0.07

As mentioned in the first answer, you can also use the function window如第一个答案中所述,您还可以使用功能window

window(gtemp, start = 1961, end = 1961)
Time Series:
Start = 1961 
End = 1961 
Frequency = 1 
[1] 0.07

that returns the result as one point time series.将结果作为一个点时间序列返回。 You can convert it into a number by您可以通过以下方式将其转换为数字

as.numeric(window(gtemp, start = 1961, end = 1961))
[1] 0.07

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM