1

I'm a beginner and I'm trying to write a function that fits a model (univariate) one variable at a time. I want to able to enter all the dependent variables when calling the function and then make the function to fit one variable at a time. Something like:

f <-function(y, x1,x2,x3) {(as.formula(print()))...}

I tried to make a list of x1, x2, x3 inside the function but it didn't work.

Maybe someone here could help me with this or point me in the right direction.

1 Answer 1

1

Here's something that might get you going. You can put your x variables inside a list, and then fit once for each element inside the list.

fitVars <- function(y, xList) {
  lapply(xList, function(x) lm(y ~ x))
}

y <- 1:10
set.seed(10)
xVals <- list(rnorm(10), rnorm(10), rnorm(10))

fitVars(y, xVals)

This returns one fit result for each element of xVals:

[[1]]

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x  
      4.984       -1.051  


[[2]]

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x  
      5.986       -1.315  


[[3]]

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x  
      7.584        2.282  

Another option is to use the ... holder to use an arbitrary number of arguments:

fitVars <- function(y, ...) {
  xList <- list(...)
  lapply(xList, function(x) lm(y ~ x))
}

set.seed(10)
fitVars(y, rnorm(10), rnorm(10), rnorm(10))

This gives the same result as above.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I solved by using the "..." almost identical like you showed in your answer. :)

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.