rformulalmr-formula

What does an ampersand in an lm formula do?


In a linear model (lm()) formula with R, what does the ampersand (&) do?

For example using a + give this result:

x <- 1:10 + rnorm(10)
z <- rep(c(0,4), 5) 
y <- x + z
lm(y ~ x + z)

Produces:

Call:
lm(formula = y ~ x + z)

Coefficients:
(Intercept)            x            z  
 -1.685e-15    1.000e+00    1.000e+00  

And using an & gives this result.

lm(y ~ x & z)

Call:
lm(formula = y ~ x & z)

Coefficients:
(Intercept)    x & zTRUE  
      4.666        5.731  

Lastly, a search for "[r] ampersand formula" on this site produced not hits, please let me know if you found an answer, what terms you used to search for.


Solution

  • In formula, it does nothing, just make independend variabla logical(or zero-one).

    > lm(y ~ x & z)
    
    Call:
    lm(formula = y ~ x & z)
    
    Coefficients:
    (Intercept)    x & zTRUE  
          5.287        4.580  
    

    You can see x & z and as.logical(z) is identical, that x does not have 0 values, so every x is TRUE.

    > x & z
     [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
    > as.logical(z)
     [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
    > as.logical(x)
     [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
    
    
    
    > lm(y ~ as.numeric(as.logical(z)))
    
    Call:
    lm(formula = y ~ as.numeric(as.logical(z)))
    
    Coefficients:
                  (Intercept)  as.numeric(as.logical(z))  
                        5.287                      4.580