简体   繁体   中英

Return value of yesterday in an xts object in R

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.

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".

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)

Which value from the previous day do you want? If you want signal from the previous day, you can't access yesterday's value before ifelse finishes producing it. Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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