Q:

Print long strings of text LaTeX / Sweave

At the end of a survey I've conducted, we give respondents an open ended box to tell us anything we didn't cover in the survey.These comments will often span several pages. I am familiar with the longtable package for LaTeX and here is the solution I have mocked up:
<<results = tex>>=
cat("\\begin{longtable}{p{14cm}}\n")
cat("\\hline\n")
write.table(toBePrinted, eol = "\\\\\n", col.names = FALSE)
cat("\\hline\n")
cat("\\end{longtable}")
@

While this solution technically works, it doesn't look terribly polished and needs to be improved. I have two related questions:

Text sanitation tips for Sweave output that is to be treated as tex. For example, if someone says Your survey is awesome & I would take more surveys for  $$$ 100% of the time! the special characters &, $, % reak havok when processing through LaTeX. Is there something more efficient than a list of gsub calls to replace the offending characters with something benevolent?
Suggestions for a better way to print these long comments with Sweave & LaTeX.

A:

You could take a look at the package xtable for creating latex tables, but that doesn't work very well with longtable I guess. Alternatively, look at the function latex in the package Hmisc, that has an option "longtable" and allows more control over the output.
To add a slash for special characters as used in Latex, you could do something like this :
add.slash <- function(x){
    where <- embed(c(1,gregexpr("[&#$%]",x)[[1]],nchar(x)+1),dim=2)
    out <- paste(apply(where,1,function(y){substr(x,y[2],y[1]-1)}),collapse="\\")
    return(out)
}

> x <- "I print $ and % and & and # and . and ! and ,"

> cat(add.slash(x),"\n")
I print \$ and \% and \& and \# and . and ! and , 

EDIT :
the use of [[:punct:]] is wrong, that also changes punctuations and so on. Code is corrected. Backslashes are really problematic.

