简体   繁体   中英

Arguments to a function in R

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.

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.

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