简体   繁体   English

R:根据条件拆分时间序列数据

[英]R: Splitting time-series data based on conditions

I am looking to split a time-series (price data) based on whether the following data-point shows an increase, decrease or no change.我希望根据以下数据点是否显示增加、减少或没有变化来拆分时间序列(价格数据)。

Example:例子:

In the set as.ts(c(1,2,3,4,5,5,4,3,2,1)) the datapoints followed by up would be 1, 2, 3, 4 .在集合as.ts(c(1,2,3,4,5,5,4,3,2,1)) ,数据点后跟 up 将是1, 2, 3, 4

I suspect this can be neatly solved with an if function, but am not sure how to specify the following row, nor am I sure as to how the syntax would look.我怀疑这可以用if函数巧妙地解决,但我不确定如何指定下一行,也不确定语法的外观。

Any help would be greatly appreciated!任何帮助将不胜感激!

You can use one of two approaches:您可以使用以下两种方法之一:

1) Using diff as follows: 1) 使用diff如下:

ifelse(diff(ts) > 0, 'up', ifelse(diff(ts) < 0, 'down', 'none'))

Output is:输出是:

Time Series:
Start = 2 
End = 10 
Frequency = 1 
[1]   up   up   up   up none down down down down

2) Using the lag function from dplyr package: 2) 使用dplyr包中的lag函数:

ifelse(ts > lag(ts), 'up', ifelse(ts < lag(ts), 'down', 'none'))

Output is as follows:输出如下:

Time Series:
Start = 1 
End = 10 
Frequency = 1 
 [1] <NA>   up   up   up   up none down down down down

You can replace the first NA by using a default in the lag or separately.您可以使用lag的默认值或单独替换第一个 NA。

EDIT: Based on additional output desired per comments below, I am editing the answer:编辑:根据下面每个评论所需的额外输出,我正在编辑答案:

You can save the result of the above in a newts - for example, and extract the original values that belong to each of the 'moves' as follows:您可以将上述结果保存在 newts 中 - 例如,并提取属于每个“移动”的原始值,如下所示:

newts <- c('up', ifelse(diff(ts) > 0, 'up', ifelse(diff(ts) < 0, 'down', 'none')))
sapply(unique(newts), function(x) ts[newts == x])

Output is as follows:输出如下:

$up
[1] 1 2 3 4 5

$none
[1] 5

$down
[1] 4 3 2 1

These are three lists.这是三个清单。 You can do whatever else you want with them, or combine them into other data structures as desired.你可以用它们做任何你想做的事情,或者根据需要将它们组合成其他数据结构。

NOTE: I am pre-pending the newts with up since the first element is an orphan with no move.注意:我将newts预先挂起,因为第一个元素是一个没有移动的孤儿。 Depending on how you want things to output, you may want to adjust this value to your taste.根据您希望事物输出的方式,您可能需要根据自己的喜好调整此值。

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

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