Search code examples
rsweavextable

Combining several regression tables into one for use in xtable with Sweave in R


xtable in Sweave works awesome, but does one table per regression. You can feed it a data frame, too, so I have been manually rbinding and pasteing results into data frames, but that doesn't seem very scalable.

Is there a more automated/robust solution that works like xtable, but on multiple lm objects? Are all of the tables that I see in papers/books generated manually? Is there a better solution to my janky code that generates a data frame to feed to xtable?

    library(reshape2)

    data <- data.frame(matrix(rnorm(50), 10, 5))
    names(data) <- letters[1:5]
    l.raw <- list()
    l.raw[["a"]] <- lm(a ~ d + e, data=data)
    l.raw[["b"]] <- lm(b ~ d + e, data=data)
    l.raw[["c"]] <- lm(c ~ d + e, data=data)

    form.table.from.lm <- function(l.raw) {
    summ <- list()

    for (i in names(l.raw)) {
        temp <- coef(summary(l.raw[[i]]))
        summ[[i]] <- data.frame(param=rownames(temp), test=i, temp)
    }

    df.res <- do.call("rbind", summ)
    df.res <- transform(df.res, t.value = paste("(", signif(t.value), ")", sep=""), Estimate = signif(Estimate))
    df.res.long <- melt(df.res, id.vars=c("test", "param"))
    df.res.wide <- dcast(df.res.long, test + variable ~ param)

    temp <- subset(df.res.wide, variable %in% c("Estimate", "t.value"))
    df.res <- temp[, -2]
    df.res[, 1] <- as.vector(rbind(names(l.raw), ""))
    colnames(df.res)[1] <- "regressor"
    return(df.res)
}

Which produces data frame:

   regressor (Intercept)          d          e
1          a    0.393996  -0.666721   0.159508
2             (0.573926) (0.422125) (0.526446)
5          b    0.611077  0.0288942   -0.70033
6              (0.32696)  (0.24048) (0.299911)
9          c   -0.101033  -0.287821    0.14581
10            (0.203193) (0.149449) (0.186383)

Given the amazing plotting packages for R, I feel like google and rseek are hiding something from me.


Solution

  • A while ago I stumbled across the outreg function by Paul Johnson.

    You can directly apply outreg to your lm object and combine several lm outputs into one, nice latex table.

    Here you find an example .pdf

    outreg examples

    and the code for the function

    outreg code

    general homepage by Paul Johnson

    Paul Johnson