Search code examples
rpastesweavetabular

data.frame columns as tabular row labels in R


I am trying to make a table in R/Sweave using the tabular command. I want the row labels to be the headings of my data frame consca. (Each column is a question, and each row is a student's responses to each question.) The command I am using is this:

latex(tabular(Heading('Questions')*(paste(labels(consca)[[2]],collapse='+')) ~ (n=1) + (mn + 
          sdev),data=consca))

Which throws this error:

Error in term2table(rows[[i]], cols[[j]], data, n) : 
Argument paste(labels(consca)[[2]], collapse = "+") is not length 298

The paste argument works...

 paste(labels(consca)[[2]],collapse='+')
    [1] "Q02+Q03+Q06+Q17+Q19+Q25+Q31+Q33+Q36+Q39+Q45+Q50"

And produces the output I desire:

latex(tabular(Heading('Questions')*(Q02+Q03+Q06+Q17+Q19+Q25+Q31+Q33+Q36+Q39+Q45+Q50) ~ (n=1) + 
                (mn + sdev),data=consca))

However, I want to do this with multiple scales (i.e. I want to change consca to other objects and I want to eliminate the copy/paste step.)

I have fiddled with eval and as.symbol, but to no avail. Perhaps I am not using them in the right way.

OK, and for those of you who will want a minimal reproducible example, here goes:

require(tables)
a <- rnorm(10)
b <- rnorm(10,2)
c <- rnorm(10,100)
x <- data.frame(a,b,c)
# This works:
tabular(a+b+c ~ (mean + sd), x)
# This fails:
tabular(paste(labels(x)[[2]],collapse='+') ~ (mean+sd),x)
# Even though:
paste(labels(x)[[2]],collapse='+')
[1] "a+b+c"

Solution

  • I found a workaround using the describe function in the psych package. (Ultimately, I wanted more than the mean and sd, and the describe function automatically calculates them.) This creates a data.frame, which is trivial to turn into a \LaTeX table. 😃