user59419
user59419

Reputation: 993

tilde(~) operator in R

According to the R documentation: ~ operator is used in formula to separate the right and left hand side of the formula. The right hand side is independent variable and the left hand side is dependent variable. I understand when ~ is used in lm() package. However what does following mean?

x~ 1

The right hand side is 1. what does it mean? Can it be any other number instead of 1?

Upvotes: 7

Views: 4818

Answers (1)

RLave
RLave

Reputation: 8364

From ?lm:

[..] when fitting a linear model y ~ x - 1 specifies a line through the origin [..]

The "-" in the formula removes a specified term.

So y ~ 1 is just a model with a constant (intercept) and no regressor.

lm(mtcars$mpg ~ 1)
#Call:
#lm(formula = mtcars$mpg ~ 1)
#
#Coefficients:
#(Intercept)  
#      20.09  

Can it be any other number instead of 1?

No, just try and see.

lm(mtcars$mpg ~ 0) tells R to remove the constant (equal to y ~ -1), and lm(mtcars$mpg ~ 2) gives an error (correctly).

You should read y ~ 1 as y ~ constant inside the formula, it's not a simple number.

Upvotes: 8

Related Questions