0

I want to regress the following equation: x5 = B0 + B1(x1-x2) + B2 * max[0,(x2 - x1)] + e

I have some trouble with generating the max[0,(x0 - x1)] variable. The variable should either be 0 if (x2-x1) is <0, or the difference between (x2-x1) if >=0.

 d1 <- structure(list(Date=c("2012-01-01", "2012-06-01",
                 "2013-01-01", "2013-06-01", "2014-01-01", "2014-06-01"),
                 x1=c(10, 12, 17L, 29L, 27L, 10L), 
                 x2=c(30L, 19L, 22L, 20L, 11L,24L), 
                 x3=c(28, 23L, 22L, 27L, 21L, 26L),
                 x4=c(30L, 28L, 23L,24L, 10L, 17L), 
                 x5=c(14, 17, 19, 16L, 30L, 26L)),
                 row.names=c(NA, 6L), class="data.frame")
 rownames(d1) <- d1[, "Date"]   
 d1 <- d1[,-1]     

Thank you

1 Answer 1

3

We can use pmax

pmax(0, d1$x2 - d1$x1)
#[1] 20  7  5  0  0 14

This returns maximum between x2 - x1 or 0.

ifelse approach would be

ifelse(d1$x2 - d1$x1 < 0, 0, d1$x2 - d1$x1)
#[1] 20  7  5  0  0 14
Sign up to request clarification or add additional context in comments.

1 Comment

A third option for fun: with(d1, (x2 - x1) * ((x2 - x1) > 0))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.