0
votes

I have this data.frame:

df <- data.frame(a=rnorm(500),b=rnorm(500),c=rnorm(500),
      d=rnorm(500),e=rnorm(500),f=rnorm(500),g=rnorm(500))

And i run quantile regression:

library(quantreg)
a<-rq(a~g,tau = 0.5,method="br",data=df)
summary.rq(a)
b<-rq(b~g,tau = 0.5,method="br",data=df)
summary.rq(b)
c<-rq(c~g,tau = 0.5,method="br",data=df)
summary.rq(c)
d<-rq(d~g,tau = 0.5,method="br",data=df)
summary.rq(d)
e<-rq(e~g,tau = 0.5,method="br",data=df)
summary.rq(e)
f<-rq(f~g,tau = 0.5,method="br",data=df)
summary.rq(f)
g<-rq(g~g,tau = 0.5,method="br",data=df)
summary.rq(g)

For example:

summary.rq(a)
Call: rq(formula = a ~ g, tau = 0.5, data = df, method = "br")

tau: [1] 0.5

Coefficients:
            coefficients lower bd upper bd
(Intercept)  0.12940      0.04870  0.17940
g           -0.02131     -0.08078  0.05370

I want to build a matrix like this:

Matrix.Parameters.Interval<-matrix(0,7,6)

the first line will be related to the first model. In the first column goes the intercept parameter the 2º and 3º column its confidence interval(that I will extract from the summary output), 4º column the variable parameter, and in the 5º and 6º column its interval (that I will extract from the summary output)

1

1 Answers

2
votes
modList <- list(a,b,c,d,e,f,g)

A function to extract information from a model and reformat it to a 1-row matrix with the information about the intercept (the first row) as the first half of the matrix and the information about the slope as the second half ...

tmpf <- function(model) {
    matrix(coef(summary(model)),nrow=1,byrow=TRUE)
}

Run on each element of the list:

t(sapply(modList[1:5],tmpf))

the t() is necessary because sapply always returns results in a column-wise fashion.

This only works for the first 5 models; the 6th model is singular because the predictor and response are the same.

A more systematic way to do this:

tmpf2 <- function(respvar) {
   fit <- rq(reformulate("g",response=respvar),
            tau = 0.5,method="br",data=df)
   matrix(coef(summary(fit)),nrow=1,byrow=TRUE)
}
t(sapply(names(df)[1:5],tmpf2))

This way you don't have to repeat code (DRY="do not repeat yourself"), and you don't have all of those fitted models cluttering your workspace.