Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tilde(~) operator in R

Tags:

r

formula

tilde

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?

like image 385
user59419 Avatar asked Dec 17 '18 09:12

user59419


1 Answers

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.

like image 199
RLave Avatar answered Oct 01 '22 00:10

RLave