[R] Help with function writing

Michael Bedward michael.bedward at gmail.com
Tue Oct 12 06:12:49 CEST 2010


Hello Tim,

This function will do it where the covariates are provided as separate
arguments. It would be easy to modify this to handle a list too.

function(outcome, ...) {
  arg.names <- as.character(match.call())[-1]
  nargs <- length(arg.names)
  f <- as.formula(paste(arg.names[1], "~", paste(arg.names[2:nargs],
collapse="+")))

  model <- lm(f)

  # rest of your code here
}

Hope that helps you get started.

Michael


On 12 October 2010 14:35, Tim Elwell-Sutton <tesutton at hku.hk> wrote:
> 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?
>
> Example:
>
> #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)
>  summary(expected)
> }
>
> library(MASS)
> attach(birthwt)
>
> 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
>
> --
> Tim Elwell-Sutton
> University of Hong Kong
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list