R 中 xts 对象中昨天的返回值
这是 xts 对象的尾部:
SPY.Close mavg dn.1 up.1
2011-02-16 133.85 132.446 128.8502 130.9545
2011-02-17 134.25 132.793 129.0212 131.2241
2011-02-18 134.53 133.131 129.2198 131.5016
2011-02-22 131.83 133.117 129.4104 131.6236
2011-02-23 131.02 132.962 129.5961 131.7072
2011-02-24 130.93 132.828 129.7575 131.7792
给定一个每天传递的简单嵌套 ifelse() 函数:
signal <- ifelse(t$mavg > t$up.1, 1, ifelse(t$mavg < t$dn.1, -1, 99))
该规则中的值可以添加到该对象中:
t$signal = signal
生成新对象(我用一节来进行说明):
SPY.Close mavg dn.1 up.1 signal
2010-11-18 119.96 120.713 118.17955 119.99845 1
2010-11-19 120.29 120.470 118.33112 120.09688 1
2010-11-22 120.19 120.240 118.47911 120.18489 1
2010-11-23 118.45 119.924 118.55112 120.20888 99
2010-11-24 120.20 119.734 118.63565 120.27635 99
如何我可以重写嵌套的 ifelse() 语句,以便每次计算结果为 99 时,都返回前一天的值吗?
注意:如果由于先有鸡还是先有蛋的悖论而无法按照指定的方式编写嵌套的 ifelse() 语句,则使用单独的语句将 99 变为 1 就足够了。
This is the tail of an xts object:
SPY.Close mavg dn.1 up.1
2011-02-16 133.85 132.446 128.8502 130.9545
2011-02-17 134.25 132.793 129.0212 131.2241
2011-02-18 134.53 133.131 129.2198 131.5016
2011-02-22 131.83 133.117 129.4104 131.6236
2011-02-23 131.02 132.962 129.5961 131.7072
2011-02-24 130.93 132.828 129.7575 131.7792
Given a simple nested ifelse() function passed across each day:
signal <- ifelse(t$mavg > t$up.1, 1, ifelse(t$mavg < t$dn.1, -1, 99))
The value from this rule can be added to the object:
t$signal = signal
Yielding the new object (I've taken a section for illustration):
SPY.Close mavg dn.1 up.1 signal
2010-11-18 119.96 120.713 118.17955 119.99845 1
2010-11-19 120.29 120.470 118.33112 120.09688 1
2010-11-22 120.19 120.240 118.47911 120.18489 1
2010-11-23 118.45 119.924 118.55112 120.20888 99
2010-11-24 120.20 119.734 118.63565 120.27635 99
How can I re-write the nested ifelse() statement so that each time it evaluates to 99, the value from the previous day is returned instead?
NOTE: if the nested ifelse() statement cannot be written as specified due to a chicken/egg paradox, then a separate statement to turn the 99 into 1 will suffice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您放弃 99 约定并使用真正的 NA。那么您应该熟悉zoo::na.locf,它的意思是“对于NA's,最后的观察结转”。
You drop the 99 convention and use real NA's. Then you should make the acquaintance of zoo::na.locf, which reads "for NA's , last observation carry forward".
您想要前一天的哪个值?如果您想要前一天的
signal
,则在ifelse
完成生成之前无法访问昨天的值。试试这个:Which value from the previous day do you want? If you want
signal
from the previous day, you can't access yesterday's value beforeifelse
finishes producing it. Try this instead: