user1431694
user1431694

Reputation: 735

R: calling rq() within a function and defining the linear predictor

I am trying to call rq() of the package quantreg within a function. Herebelow is a simplified explanation of my problem.

If I follow the recommendations found at http://developer.r-project.org/model-fitting-functions.txt, I have a design matrix after the line

x <- model.matrix(mt, mf, contrasts)

with the first column full of 1's to create an intercept.

Now, when I call rq(), I am obliged to use something like

fit <- rq (y ~ x [,2], tau = 0.5, ...)

My problem happens if there is more than 1 explanatory variable. I don't know how to find an automatic way to write:

x [,2] + x [,3] + x [,4] + ...

Here is the complete simplified code:

ao_qr <- function (formula, data, method = "br",...) {

cl <- match.call ()

## keep only the arguments which should go into the model 
## frame

mf <- match.call (expand.dots = FALSE)

m <- match (c ("formula", "data"), names (mf), 0)

mf <- mf[c (1, m)]

mf$drop.unused.levels <- TRUE

mf[[1]] <- as.name ("model.frame")

mf <- eval.parent (mf)

if (method == "model.frame") return (mf)

## allow model.frame to update the terms object before 
## saving it

mt <- attr (mf, "terms") 

y <- model.response (mf, "numeric")

x <- model.matrix (mt, mf, contrasts)

## proceed with the quantile regression

fit <- rq (y ~ x[,2], tau = 0.5, ...)

print (summary (fit, se = "boot", R = 100))
}

I call the function with:

ao_qr(pain ~ treatment + extra, data = data.subset) 

And here is how to get the data:

require (lqmm)
data(labor)
data <- labor

data.subset <- subset (data, time == 90)
data.subset$extra <- rnorm (65) 

In this case, with this code, my linear predictor only includes "treatment". If I want "extra", I have to manually add x[,3] in the linear predictor of rq() in the code. This is not automatic and will not work on other datasets with unknown number of variables. Does anyone know how to tackle this ?

Any help would be greatly appreciated !!!

Upvotes: 0

Views: 628

Answers (1)

user1431694
user1431694

Reputation: 735

I found a simple solution: x[,2:ncol(x)]

Upvotes: 1

Related Questions