Pogi93
Pogi93

Reputation: 63

Creating a variable with a function in R

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

Upvotes: 0

Views: 34

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

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

Upvotes: 3

Related Questions