Erkan AĞASLAN
Erkan AĞASLAN

Reputation: 41

Using variable as function argument in r

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?

Upvotes: 1

Views: 267

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 546045

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)

Upvotes: 1

MrFlick
MrFlick

Reputation: 206536

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

Upvotes: 2

Related Questions