If-else depending on the previous value
I want to create a vector z
that only contains 1 or -1. If 1 or -1 is required, depends on the RSI value:
If RSI is greater than 70, z should be -1 If RSI is less than 30, z should be 1
For all other cases: z
must have the same number as the previous one z
.
It meansz = z(t-1)
RSI is a vector containing numbers from 0 to 100. So far, I've used a condition ifelse
.
rsi <- RSI(YENDOL, n=14)
z <- 0
z <- ifelse(rsi >= 70,-1,z)
z <- ifelse(rsi <= 30,1,z)
With this, I created a vector z
containing 0, 1 and -1. The next step would be to change the zeros to 1 or -1 depending on the previous value (z t-1)
. This is where I am stuck. I will need the vector later to multiply it with another vector.
Using the package na.locf
from zoo
, example:
library(zoo)
#data
set.seed(123)
rsi <- round(runif(10,0,100))
rsi
#[1] 29 79 41 88 94 5 53 89 55 46
#apply condition to set -1 and 1
z <- ifelse(rsi >= 70,-1, ifelse(rsi <= 30,1,NA))
z
#[1] 1 -1 NA -1 -1 1 NA -1 NA NA
#Then use zoo function to fill in the NAs with previous non NA value
z <- na.locf(z)
z
#[1] 1 -1 -1 -1 -1 1 1 -1 -1 -1