Search code examples
rif-statementrstudioxtsdummy-variable

How do I create an XTS of dummy variables from another XTS?


Suppose I have the following xts...

a <- c(1,-1,2,-2)
b <- c(-1,-2,3,4)
x <- xts(cbind(a,b),order.by = as.Date(c("2015-01-02","2015-01-05","2015-01-06","2015-01-07")))
x

This gives you...

            a  b
2015-01-02  1 -1
2015-01-05 -1 -2
2015-01-06  2  3
2015-01-07 -2  4

I want to create an xts of dummy variables that take the value 1 when the value is greater than 0 and 0 and when value is less than or equal to 0. So I'd like to get this...

            a  b
2015-01-02  1  0
2015-01-05  0  0
2015-01-06  1  1
2015-01-07  0  1

I tried the following code but it didn't work...

y <- ifelse(x>0,1,0)
y

Solution

  • Here is an option where we convert the logical to binary with as.integer and assign the results back to the original dataset

    x[] <- as.integer(x > 0)
    

    Or using arithmetic

    (x > 0) * 1
    #           a b
    #2015-01-02 1 0
    #2015-01-05 0 0
    #2015-01-06 1 1
    #2015-01-07 0 1
    

    Or another option is

    (x > 0) + 0