[R] Help with function writing

Tim Elwell-Sutton tesutton at hku.hk
Tue Oct 12 05:35:13 CEST 2010

Hello all
I have what seems like a simple question but have not been able to find an
answer on the forum. I'm trying to define a function which involves
regression models and a large number of covariates. 

I would like the function to accept any number of covariates and, ideally, I
would like to be able to enter the covariates in a group (e.g. as a list)
rather than individually. Is there any way of doing this? 


#define function involving regression model with several covariates 
custom <- function(outcome, exposure, covar1, covar2, covar3){
  model <- lm(outcome ~ exposure + covar1 +  covar2 + covar3)
  expected <- predict(model)


custom(bwt, lwt, low, age, race) #Works when 3 covariates are specified

custom(bwt,lwt,low,age) # Does not work with < or > 3 covariates

varlist <- list(low,age,race)
custom(bwt,lwt, varlist) #Does not work if covariates are included as a list

Thanks very much for your help


Tim Elwell-Sutton
University of Hong Kong

More information about the R-help mailing list