在R中的xts对象中返回昨天的值

时间:2011-02-25 03:25:26

标签: 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的单独语句就足够了。

2 个答案:

答案 0 :(得分:4)

你删除99惯例并使用真正的NA。那么你应该结识一下zoo :: na.locf,其中写着“对于NA,最后一次观察结转”。

M <- read.table(textConnection(" SPY.Close    mavg      dn.1      up.1
2010-11-18    119.96 120.713 118.17955 119.99845   
2010-11-19    120.29 120.470 118.33112 120.09688   
2010-11-22    120.19 120.240 118.47911 120.18489   
2010-11-23    118.45 119.924 118.55112 120.20888   
2010-11-24    120.20 119.734 118.63565 120.27635   
") )
M <- cbind(M, signal = ifelse(M$mavg > M$up.1, 1, ifelse(M$mavg < M$dn.1, -1, NA)) )
M$signal <- na.locf(M$signal)

答案 1 :(得分:0)

您想要前一天的哪个值?如果您想要前一天的signal,则在ifelse完成生成之前,您无法访问昨天的值。试试这个:

tick$lagsignal <- c(NA, head(tick$signal, -1))
tick$newsignal <- ifelse(tick$signal == 99, tick$lagsignal, tick$signal)