1

I want to control a linear regression model with a specific variable. If i assign variable "c" as 0, i want to estimate the model:

lm(y ~ x)    # model with intercept

and if i assign variable "c" as 1 i want to estimate:

lm(y ~ x - 1) # model without intercept

I tried the code below

c <- 1
lm(y ~ x - c)

but it didn't work. c is 1 but in lm function i can't use this variable for argument. How can i assign and use a variable to add intercept and remove?

2 Answers 2

2

I don't think you can do that with a simple variable. Rather than conditionally setting the value of a, you can conditionally remove the intercept. Something like

myformula <- y~x
if(TRUE) {
  myformula <- update(myformula, ~.-1)
}
myformula
# y ~ x - 1
Sign up to request clarification or add additional context in comments.

Comments

1

Formula objects don’t evaluate their arguments (otherwise they fundamentally wouldn’t work). So you need to find a way of interpolating an evaluated value into the unevaluated formula expression.

Like all problems of computer science, this can be solved by one more layer of indirection.

Create an unevaluated expression that creates your formula, and evaluate it after interpolating the variable:

formula = eval(bquote(y ~ x - .(c)))
lm(formula)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.