R exams package weird behaviour with dplyr - r

I have noted to strange behaviour in the R exams package when I load the dplyr library. the below example only works if I explicitly call the dplyr namespace, as indicated in the comments. notice that the error only occurs in a fresh session, i.e. you need to restart R in order to see what I see. You need to place the below in a file exam.Rmd, then call
library(exams)
library(dplyr)
exams2html("exam.Rmd") # in pwd
# this is exam.Rmd
```{r datagen,echo=FALSE,results='hide',warning=FALSE,message=FALSE}
df = data.frame(i = 1:4, y = 1:4, group = paste0("g",rep(1:2,2)))
# works:
b2 = diff(dplyr::filter(df,group!="g1")$y)
b3 = diff(dplyr::filter(df,group!="g2")$y)
# messes up the complete exercise:
# b2 = diff(filter(df,group!="g1")$y)
# b3 = diff(filter(df,group!="g2")$y)
nq = 2
questions <- solutions <- explanations <- rep(list(""), nq)
type <- rep(list("num"),nq)
questions[[1]] = "What is the value of $b_2$ rounded to 3 digits?"
questions[[2]] = "What is the value of $b_3$ rounded to 3 digits?"
solutions[[1]] = b2
solutions[[2]] = b3
explanations[[1]] = paste("You have you substract the conditional mean of group 2 from the reference group 1. gives:",b2)
explanations[[2]] = paste("You have you substract the conditional mean of group 3 from the reference group 1",b3)
```
Question
========
You are given the following dataset on two variables `y` and `group`.
```{r showdata,echo=FALSE}
# kable(df,row.names = FALSE,align = "c")
df
```
some text with math
$y_i = b_0 + b_2 g_{2,i} + b_3 g_{3,i} + e_i$
```{r questionlist, echo = FALSE, results = "asis"}
answerlist(unlist(questions), markup = "markdown")
```
Solution
========
```{r sollist, echo = FALSE, results = "asis"}
answerlist(unlist(explanations), markup = "markdown")
```
Meta-information
================
extype: cloze
exsolution: `r paste(solutions,collapse = "|")`
exclozetype: `r paste(type, collapse = "|")`
exname: Dummy Manual computation
extol: 0.001

Thanks for raising this issue and to #hrbrmstr for explanation of one part of the problem. However, one part of the explanation is still missing:
Of course, the root of the problem is that both stats and dplyr export different filter() functions. And it can depend on various factors which function is found first.
In an interactive session it is sufficient to load the packages in the right order with stats being loaded automatically and dplyr subsequently. Hence this works:
library("knitr")
library("dplyr")
knit("exam.Rmd")
It took me a moment to figure out what is different when you do:
library("exams")
library("dplyr")
exams2html("exam.Rmd")
It turns out that in the latter code chunk knit() is called by exams2html() and hence the NAMESPACE of the exams package changes the search path because it fully imports the entire stats package. Therefore, stats::filter() is found before dplyr::filter() unless the code is evaluated in an environment where dplyr was loaded such as the .GlobalEnv. (For more details see the answer by #hrbrmstr)
As there is no pressing reason for the exams package to import the entire stats package, I have changed the NAMESPACE to import only the required functions selectively (which does not include the filter() function). Please install the development version from R-Forge:
install.packages("exams", repos = "http://R-Forge.R-project.org")
And then your .Rmd can be compiled without dplyr::... just by including library("dplyr") - either within the .Rmd or before calling exams2html(). Both should work now as expected.

Using your exams.Rmd, this is the source pane where I'm about to hit cmd-enter:
(I added quiet=FALSE so I could see what was going on).
Here's the console output after cmd-enter:
And here's the output:
If you read all the way through to the help on knit:
envir: Environment in which code chunks are to be evaluated, for example, parent.frame(), new.env(), or globalenv()).
So parent.frame() or globalenv() is required vs what you did (you don't seem to fully understand environments). You get TRUE from your exists() call because by default inherits is TRUE in the exists function and that tells the function to "[search] the enclosing frames of the environment" (from the help on exists.
And, you should care deeply about source code and triaging errors. You're using a programming language and open source software and you are right that the library(dplyr) didn't work inside the Rmd due to some terrible code choices in this "great" package and that you don't want pointed out since you don't want to look at source code.
End, as I can do no more for you. I just hope others benefit from this.

Related

Using R/exams in bookdown document (especially for HTML output)

I have created a "book" using bookdown. I would love to be able to add interactive quizzes, without needing shiny etc.
Is it possible using R/exams (http://www.R-exams.org/) with bookdown? I'm mainly interested in the HTML output; PDF output a bonus but hardly essential. The web page offers promise:
Based on (potentially) dynamic exercise templates large numbers of personalized exams/quizzes/tests can be created for various systems: [...] and the possibility to create custom output (in PDF, HTML, Docx, ...).
Exercise types include multiple-choice or single-choice questions, numeric or text answers, or combinations of these. Formatting can be done either in Markdown or LaTeX with the possibility to generate dynamic content using R, e.g., random numbers, graphics, data sets, or shuffled text blocks.
It sounds great. Does anyone know if it is possible to use exams with bookdown (even if just some features)?
If it is possible: how? Any pointers?
If it is not possible: does anyone know a way to do something similar?
General remarks
R/exams is indeed extensible leveraging its building blocks is relatively easy. The workhorse function underlying all the exams2xyz() interfaces is called xexams(). It proceeds in four steps:
sweave: The exercise files are copied to a temporary directory and then run through R, by default using xweave() which provides a unified convenience interface to utils::Sweave() (for Rnw files) and knitr::knit() (for Rmd files).
read: The resulting weaved files are read into R, by default using read_exercise(). For each exercise this yields a list of question, questionlist, solution, solutionlist, metainfo, and supplements. All elements are always there but may be empty, e.g., when there is no solution environment provided in the exercise or when there are no supplementary files.
transform: By default this is empty but can be used to transform the exercise list elements above to a desired format, e.g., HTML.
write: By default this is empty, but can be used to write out results for each of the n replications of the exam.
Embedding exercise texts in Markdown
When you write your exercises in R/Markdown (Rmd) files you can easily run them through xexams() to get some randomized version of them. As an example, let's consider the numeric (num) and single-choice (schoice) version of the derivative exercise, see: deriv, deriv2. Using 1 as the random seed, the numeric exercise has the following question along with the correct solution and tolerance:
set.seed(1)
d1 <- xexams("deriv.Rmd")[[1]][[1]]
d1$question
## [1] "What is the derivative of $f(x) = x^{2} e^{2.3 x}$, evaluated at $x = 0.56$?"
d1$metainfo$solution
## [1] 6.68
d1$metainfo$tolerance
## [1] 0.01
The reason for the [[1]][[1]] index is that this is from the first (and only) exam, the first (and only) exercise. If you generate, say, xexams(..., n = 3) then the first index could be in 1, 2, 3. Similarly, you could inlude more than one exercise if you want.
The single-choice version has
set.seed(1)
d2 <- xexams("deriv2.Rmd")[[1]][[1]]
d2$question
## [1] "What is the derivative of $f(x) = x^{2} e^{2.3 x}$, evaluated at $x = 0.66$?"
## [2] ""
d2$questionlist
## [1] "$8.01$" "$14.09$" "$10.59$" "$15.35$" "$6.02$"
d2$metainfo$solution
## [1] FALSE FALSE TRUE FALSE FALSE
Both of these would be very easy to integrate as static text into any R/Markdown document.
Embedding exercise texts in webex
To turn the static text into a dynamic element in HTML, e.g., a text field where readers could enter a number which is then compared with the reference value from the solution, it is possible to employ Javascript for example. One lightweight R-based framework for generating such output is the webex package by Dale Barr and Lisa DeBruine.
In webex you can create fill-in-the-blank interactions via fitb() for numeric solutions with an optional tolerance (num in R/exams) or for character solutions (string in R/exams). Also, you can create drop-down menu interactions via mcq() for single-choice questions (schoice in R/exams). (Note: The jargon regarding choice questions is not unified: What R/exams calls single-choice is also referred to as multiple-choice. In this case multiple-answer is often used for what R/exams calls multiple-choice.)
At the moment, webex does not support radio buttons as an alternative to drop-down menus. Also, check-boxes for multiple-choice (aka multiple-answer) questions is not available.
Below, I illustrate how to embed simple schoice, num, and string questions in webex. For more elaborate examples with supplementary files, see the comments below. Also, cloze would also be doable but take some more work.
---
title: "Web Exercises with R/exams & webex"
output: webex::webex_default
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)
library("webex")
library("exams")
```
`r style_widgets("#DF536B", "#61D04F")`
## `schoice`
```{r swisscapital, echo = FALSE, results = "asis"}
x <- xexams("swisscapital.Rmd")[[1]][[1]]
names(x$questionlist) <- ifelse(x$metainfo$solution, "answer", "")
x <- c(
x$question,
"",
mcq(x$questionlist),
"",
hide("Correct solution"),
"",
x$solution,
"",
paste("*", x$solutionlist),
"",
unhide()
)
writeLines(x)
```
## `num`
```{r deriv, echo = FALSE, results = "asis"}
x <- xexams("deriv.Rmd")[[1]][[1]]
x <- c(
x$question,
"",
fitb(x$metainfo$solution, tol = x$metainfo$tol,
width = min(100, max(20, nchar(x$metainfo$solution)))),
"",
hide("Correct solution"),
"",
x$solution,
"",
unhide()
)
writeLines(x)
```
## `string`
```{r function, echo = FALSE, results = "asis"}
x <- xexams("function.Rmd")[[1]][[1]]
x <- c(
x$question,
"",
fitb(x$metainfo$solution, width = min(100, max(20, nchar(x$metainfo$solution)))),
"",
hide("Correct solution"),
"",
x$solution,
"",
unhide()
)
writeLines(x)
```
Rendering this with rmarkdown::render() gives you a file like shown in the screenshot below. When embedding this in bookdown you need to make sure to embed the webex.css and webex.js from the package.
Further variations
Some extra work is involved when processing exercises that contain images such as boxplots. The default in xexams() is set up for PDF output but the driver$sweave can be tweaked to produce PNG output. In either case, the supplements is then a vector of file paths to the supplementary files:
set.seed(1)
b1 <- xexams("boxplots.Rmd", driver = list(sweave = list(png = TRUE)))[[1]][[1]]
b1$question
## [1] "In the following figure the distributions of a variable"
## [2] "given by two samples (A and B) are represented by parallel boxplots."
## [3] "Which of the following statements are correct? _(Comment: The"
## [4] "statements are either about correct or clearly wrong.)_"
## [5] "\\"
## [6] "![](boxplot-1.png)"
## [7] ""
b1$supplements
## boxplot-1.png
## "/tmp/RtmpA07Hau/file11d77d212e69bf/exam1/exercise1/boxplot-1.png"
## attr(,"dir")
## [1] "/tmp/RtmpA07Hau/file11d77d212e69bf/exam1/exercise1"
Additionally, you can set up a transform driver that converts the R/Markdown already to HTML (rather than having bookdown doing this later on). Here I'm selecting pandoc as the converter, using MathJax for the rendering of mathematical content (like bookdown does as well). Using base64 = TRUE instead of the FALSE below would embed the supplementary PNG image directly in the HTML code using a Base 64 encoding.
set.seed(1)
htmltrafo <- make_exercise_transform_html(converter = "pandoc-mathjax", base64 = FALSE)
b2 <- xexams("boxplots.Rmd", driver = list(sweave = list(png = TRUE), transform = htmltrafo))[[1]][[1]]
b2$question
## [1] "<p>In the following figure the distributions of a variable given by two samples (A and B) are represented by parallel boxplots. Which of the following statements are correct? <em>(Comment: The statements are either about correct or clearly wrong.)</em><br />"
## [2] "<img src=\"boxplot-1.png\" /></p>"
This is Great Achim. I was struggling to find a way to make bookdown talk to exam exercise files and found similar solution before reaching this post. The main difference is that I'm using bootstrap 4 (bookdown::bs4_book) in the html, which looks nicer.
This is how it looks in the Rmarkdown chapter file:
f_in <- fs::dir_ls('00-EOCE-Rmd/Cap08-Programação/',
type = 'file')
build_exercises(f_in, type_doc = my_engine)
The result:

rstudio hangs and aborts with rmarkdown loop

I have several datasets each of which have a common grouping factor. I want to produce one large report with separate sections for each grouping factor. Therefore I want to re-run a set of rmarkdown code for each iteration of the grouping factor.
Using the following approach from here doesnt work for me. i.e.:
---
title: "Untitled"
author: "Author"
output: html_document
---
```{r, results='asis'}
for (i in 1:2){
cat('\n')
cat("#This is a heading for ", i, "\n")
hist(cars[,i])
cat('\n')
}
```
Because the markdown I want to run on each grouping factor does not easily fit within one code chunk. The report must be ordered by grouping factor and I want to be able to come in and out of code chunks for each iteration over grouping factor.
So I went for calling an Rmd. with render using a loop from an Rscript for each grouping factor as found here:
# run a markdown file to summarise each one.
for(each_group in the_groups){
render("/Users/path/xx.Rmd",
output_format = "pdf_document",
output_file = paste0(each_group,"_report_", Sys.Date(),".pdf"),
output_dir = "/Users/path/folder")
}
My plan was to then combine the individual reports with pdftk. However, when I get to the about the 5th iteration my Rstudio session hangs and eventually aborts with a fatal error. I have ran individually the Rmd. for the grouping factors it stops at which work fine.
I tested some looping with the following simple test files:
.R
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
# use first 5 rows of mtcars as example data
mtcars <- mtcars[1:5,]
# for each type of car in the data create a report
# these reports are saved in output_dir with the name specified by output_file
for (car in rep(unique(rownames(mtcars)), 100)){
# for pdf reports
rmarkdown::render(input = "/Users/xx/Desktop/2.Rmd",
output_format = "pdf_document",
output_file = paste("test_report_", car, Sys.Date(), ".pdf", sep=''),
output_dir = "/Users/xx/Desktop")
}
.Rmd
```{r, include = FALSE}
# packages
library(knitr)
library(markdown)
library(rmarkdown)
library(tidyr)
library(dplyr)
library(ggplot2)
```
```{r}
# limit data to car name that is currently specified by the loop
cars <- mtcars[rownames(mtcars)==car,]
# create example data for each car
x <- sample(1:10, 1)
cars <- do.call("rbind", replicate(x, cars, simplify = FALSE))
# create hypotheical lat and lon for each row in cars
cars$lat <- sapply(rownames(cars), function(x) round(runif(1, 30, 46), 3))
cars$lon <- sapply(rownames(cars), function(x) round(runif(1, -115, -80),3))
cars
```
Today is `r Sys.Date()`.
```{r}
# data table of cars sold
table <- xtable(cars[,c(1:2, 12:13)])
print(table, type="latex", comment = FALSE)
```
This works fine. So I also looked at memory pressure while running my actual loop over the Rmd. which gets very high.
Is there a way to reduce memory when looping over a render call to an Rmd. file?
Is there a better way to create a report for multiple grouping factors than looping over a render call to an Rmd. file, which doesn't rely on the entire loop being inside one code chunk?
Found a solution here rmarkdown::render() in a loop - cannot allocate vector of size
knitr::knit_meta(class=NULL, clean = TRUE)
use this line before the render line and it seems to work
I am dealing with the same issue now and it's very perplexing. I tried to create some simple MWEs but they loop successfully on occasion. So far, I've tried
Checking the garbage collection between iterations of rmarkdown::render. (They don't reveal any special accumulations.)
Removing all inessential objects
Deleting any cached files manually
Here is my question:
How can we debug hangs? Should we set up special log files to understand what's going wrong?

Inexplicable error when trying to export my R notebook

Getting this error from R Markdown when trying to export my .RMD
"Error in filter(Gastropods, Species == "Cellana") : object 'Species' not found Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> filter"
However, all my plots are coming out successfully. I can clearly see in the data that the species column is there and that Cellana is a species. No spelling errors or anything.
My first 20 or so lines of code are below
###
---
title: " Lab Report 2 - z5016113"
output: html_notebook
i---
#1. Gastropod abundance vs. height on the shore
```{r}
Gastropods <- read.csv(file = "MaroubraZones.csv", header = TRUE)
library(ggplot2, dplyr)
```
```{r}
Gastropods$Zone <- factor(Gastropods$Zone, levels = c("Low", "Mid", "High"))
```
```{r}
Cellana <- filter(Gastropods, Species == "Cellana") ------> This line is causing the error
```
```{r}
ggplot(Cellana, aes(Zone, Abundance)) + geom_boxplot()
```
###
It looks like this might be a bigger issue with DPLYR and filter and I found other posts suggesting they had the same problem and the answer seemed to add dplyr::filter rather than just filter in the command. Link to a similar issue
It might also be worth testing this by filtering out the mollusc of interest before you convert it to a factor?
I have also had similar issues filtering items out and a restart of R fixed the issue.
dplyr::filter has not been found because you haven't loaded dplyr, but since there are other function named filter in other packages, it tries to apply those instead (and fails).
From ?library:
library(package, [...])
[...]
package the name of a package, given as a name or literal
character string, or a character string, depending on whether
character.only is FALSE (default) or TRUE).
This means you can only load one package at a time. Here, you are trying to load both ggplot2 and dplyr in the same call. Only ggplot2 is loaded. The correct way to do this is:
library(dplyr)
library(ggplot2)

Use variable in Sweave code chunk

I am trying to write a vignette based on some example data included with my package. I want the vignette to be as robust as possible to minor changes in example dataset -- for example an id changing.
What I was hoping to do is to define the ids in a hidden code chunk:
<<echo=FALSE, results=hide>>=
ex_id <- functionToGetID() ## Let's assume it returns 1.
#
Then use that variable to insert into functions later in the document. Something like:
<<>>=
someFunction(id = get("ex_id"))
#
The goal is for the text in the vignette to show:
someFunction(id = 1) ## and NOT someFunction(id = get("ex_id"))
I am not sure how to inject a variable into the code chunk, such that the LaTeX result only shows the value of the variable, and not how the variable was called.

Tools for making latex tables in R [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
On general request, a community wiki on producing latex tables in R. In this post I'll give an overview of the most commonly used packages and blogs with code for producing latex tables from less straight-forward objects. Please feel free to add any I missed, and/or give tips, hints and little tricks on how to produce nicely formatted latex tables with R.
Packages :
xtable : for standard tables of most simple objects. A nice gallery with examples can be found here.
memisc : tool for management of survey data, contains some tools for latex tables of (basic) regression model estimates.
Hmisc contains a function latex() that creates a tex file containing the object of choice. It is pretty flexible, and can also output longtable latex tables. There's a lot of info in the help file ?latex
miscFuncs has a neat function 'latextable' that converts matrix data with mixed alphabetic and numeric entries into a LaTeX table and prints them to the console, so they can be copied and pasted into a LaTeX document.
texreg package (JSS paper) converts statistical model output into LaTeX tables. Merges multiple models. Can cope with about 50 different model types, including network models and multilevel models (lme and lme4).
reporttools package (JSS paper) is another option for descriptive statistics on continuous, categorical and date variables.
tables package is perhaps the most general LaTeX table making package in R for descriptive statistics
stargazer package makes nice comparative statistical model summary tables
Blogs and code snippets
There is the outreg function of Paul Johnson that gives Stata-like tables in Latex for the output of regressions. This one works great.
As given in an earlier question, there's a code snippet to adapt the memisc package for lme4 objects.
Related questions :
Suggestion for R/LaTeX table creation package
Rreport/LaTeX quality output package
sorting a table for latex output with xtable
Any way to produce a LaTeX table from an lme4 mer model fit object?
R data.frame with stacked specified titles for latex output with xtable
Automating adding tables fast to latex from R, with a very flexible and interesting syntax using the formula language
I'd like to add a mention of the "brew" package. You can write a brew template file which would be LaTeX with placeholders, and then "brew" it up to create a .tex file to \include or \input into your LaTeX. Something like:
\begin{tabular}{l l}
A & <%= fit$A %> \\
B & <%= fit$B %> \\
\end{tabular}
The brew syntax can also handle loops, so you can create a table row for each row of a dataframe.
Thanks Joris for creating this question. Hopefully, it will be made into a community wiki.
The booktabs packages in latex produces nice looking tables. Here is a blog post on how to use xtable to create latex tables that use booktabs
I would also add the apsrtable package to the mix as it produces nice looking regression tables.
Another Idea: Some of these packages (esp. memisc and apsrtable) allow easy extensions of the code to produce tables for different regression objects. One such example is the lme4 memisc code shown in the question. It might make sense to start a github repository to collect such code snippets, and over time maybe even add it to the memisc package. Any takers?
The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.
I have a few tricks and work arounds to interesting 'features' of xtable and Latex that I'll share here.
Trick #1: Removing Duplicates in Columns and Trick #2: Using Booktabs
First, load packages and define my clean function
<<label=first, include=FALSE, echo=FALSE>>=
library(xtable)
library(plyr)
cleanf <- function(x){
oldx <- c(FALSE, x[-1]==x[-length(x)])
# is the value equal to the previous?
res <- x
res[oldx] <- NA
return(res)}
Now generate some fake data
data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
size=rnorm(100,mean=500, sd=150),
age=rlnorm(100, meanlog=3, sdlog=0.5))
#generate a table
datatable<-ddply(data, .(animal, colour), function(df) {
return(data.frame(size=mean(df$size), age=mean(df$age)))
})
Now we can generate a table, and use the clean function to remove duplicate entries in the label columns.
cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
#
this is a normal xtable
<<label=normal, results=tex, echo=FALSE>>=
print(
xtable(
datatable
),
tabular.environment='longtable',
latex.environments=c("center"),
floating=FALSE,
include.rownames=FALSE
)
#
this is a normal xtable where a custom function has turned duplicates to NA
<<label=cleandata, results=tex, echo=FALSE>>=
print(
xtable(
cleandata
),
tabular.environment='longtable',
latex.environments=c("center"),
floating=FALSE,
include.rownames=FALSE
)
#
This table uses the booktab package (and needs a \usepackage{booktabs} in the headers)
\begin{table}[!h]
\centering
\caption{table using booktabs.}
\label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>=
mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
foo<-0:(length(mat$animal))
bar<-foo[!is.na(mat$animal)]
print(mat,
sanitize.text.function = function(x){x},
floating=FALSE,
include.rownames=FALSE,
hline.after=NULL,
add.to.row=list(pos=list(-1,bar,nrow(mat)),
command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
#could extend this with \cmidrule to have a partial line over
#a sub category column and \addlinespace to add space before a total row
#
Two utilities in package taRifx can be used in concert to produce multi-row tables of nested heirarchies.
library(datasets)
library(taRifx)
library(xtable)
test.by <- bytable(ChickWeight$weight, list( ChickWeight$Chick, ChickWeight$Diet) )
colnames(test.by) <- c('Diet','Chick','Mean Weight')
print(latex.table.by(test.by), include.rownames = FALSE, include.colnames = TRUE, sanitize.text.function = force)
# then add \usepackage{multirow} to the preamble of your LaTeX document
# for longtable support, add ,tabular.environment='longtable' to the print command (plus add in ,floating=FALSE), then \usepackage{longtable} to the LaTeX preamble
... and Trick #3 Multiline entries in an Xtable
Generate some more data
moredata<-data.frame(Nominal=c(1:5), n=rep(5,5),
MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4),
LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4),
QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))
names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")
Now produce our xtable, using the sanitize function to replace column names with the correct Latex newline commands (including double backslashes so R is happy)
<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo,
floating=FALSE,
include.rownames=FALSE,
sanitize.text.function = function(str) {
str<-gsub("\n","\\\\", str, fixed=TRUE)
return(str)
},
sanitize.colnames.function = function(str) {
str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
return(str)
})
#
(although this isn't perfect, as we need \tabularnewline so the table is formatted correctly, and Xtable still puts in a final \, so we end up with a blank line below the table header.)
You can also use the latextable function from the R package micsFuncs:
http://cran.r-project.org/web/packages/miscFuncs/index.html
latextable(M) where M is a matrix with mixed alphabetic and numeric entries outputs a basic LaTeX table onto screen, which can be copied and pasted into a LaTeX document. Where there are small numbers, it also replaces these with index notation (eg 1.2x10^{-3}).
Another R package for aggregating multiple regression models into LaTeX tables is texreg.

Resources