[R] mapply, coxph, and model formula

Thomas Lumley tlumley at u.washington.edu
Thu Nov 8 22:58:24 CET 2007


On Thu, 8 Nov 2007, Erik Iverson wrote:

> Hello -
>
> I am wanting to create some Cox PH models with coxph (in package
> survival) using different datasets.
>
> The code below illustrates my current approach and problem with
> completing this.
>
> ### BEGIN R SAMPLE CODE ##############################
> library(survival)
>
> #Define a function to make test data
> makeTestDF <- function(n) {
>   times  <- sample(1:200, n, replace = TRUE)
>   event  <- rbinom(n, 1, prob = .1)
>   trt    <- rep(c("A","B"), each = n/2)
>   testdf <- data.frame(times,event,trt)
> }
>
> #Create two sets of test data of different sizes
> testdf1 <- makeTestDF(100)
> testdf2 <- makeTestDF(200)
>
> #Define a formula and call coxph
> form <- Surv(times, event) ~ trt
> coxph(form, testdf1) #Works
> coxph(form, testdf2) #Works
>
> #Create a list of the two data.frames
> df.list <- list(testdf1, testdf2)
>
> #Try to use mapply
> mapply(coxph, form, df.list)
>
> ### END R SAMPLE CODE ###############################
>
> The mapply call generates the following message:
>
> Error in terms.default(formula, special, data = data) :
> 	no terms component
>
> It appears from debugging that the formula argument passed into coxph is
> simply `~` in this case, with class "name" instead of "formula".
>

All the arguments to mapply have to be lists or vectors, and they are 
passed one element at a time, so what you are seeing is the first element 
of the formula.

You can use the MoreArgs argument to pass constant arguments such as form, 
or you can capture them in a closure
   mapply(function(data) {coxph(form, data=data)}, df.list)

In your case you have only one varying argument, so you could use
   lapply(df.list, coxph, formula=form)
or
   lapply(df.list, function(df) coxph(form, data=df))


 	-thomas



More information about the R-help mailing list