specifying a regression in R with an indicator variable

formula, r, regression

Solution

The ":" (colon) operator is used to construct conditional interactions (when used with disjoint predictors constructed with `I`). Should be used with predict

> y=rnorm(10)
> x=rnorm(10)
> z=rnorm(10)
> mod <- lm(y ~ x:I(z>0) )
> mod

Call:
lm(formula = y ~ x:I(z > 0))

Coefficients:
    (Intercept)  x:I(z > 0)FALSE   x:I(z > 0)TRUE  
      -0.009983        -0.203004        -0.655941  

> predict(mod, newdata=data.frame(x=1:10, z=c(-1, 1)) )
         1          2          3          4          5          6          7 
-0.2129879 -1.3218653 -0.6189968 -2.6337471 -1.0250057 -3.9456289 -1.4310147 
         8          9         10 
-5.2575108 -1.8370236 -6.5693926 
> plot(1:10, predict(mod, newdata=data.frame(x=1:10, z=c(-1)) )  )
> lines(1:10, predict(mod, newdata=data.frame(x=1:10, z=c(1)) ) )

Might help to look at its model matrix:

> model.matrix(mod)
   (Intercept) x:I(z > 0)FALSE x:I(z > 0)TRUE
1            1      -0.2866252     0.00000000
2            1       0.0000000    -0.03197743
3            1      -0.7427334     0.00000000
4            1       2.0852202     0.00000000
5            1       0.8548904     0.00000000
6            1       0.0000000     1.00044600
7            1       0.0000000    -1.18411791
8            1       0.0000000    -1.54110256
9            1       0.0000000    -0.21173300
10           1       0.0000000     0.17035257
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$`I(z > 0)`
[1] "contr.treatment"

Problem

I would like to specify a regression in R that would estimate coefficients on `x` that are conditional on a third variable, `z`, being greater than 0. For example ``` y ~ a + x*1(z>0) + x*1(z<=0) ``` What is the correct way to do this in R using formulas?

Original source