简体   繁体   中英

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM