简体   繁体   中英

Accents and xtable linebreaks for a PDF document generated with knitr

I'm using knitr package to write a PDF document. I have got several long strings character (some sentences) in a dataframe. I just want to make a simple xtable of these sentences in a PDF document.

But I got two problems :

1) I can't see the accents (I'm french so there's a lot of them in my sentences). So I tried to replace é by \\'{e} for exemple (I did for the other accents to). Here is an example :

> string<-"Compétences et gentillese remarquables."
> string<-gsub("é","\\'{e}",string)
> string
[1] "Comp'{e}tences et gentillese remarquables."

I don't have any backslash... and that will not work in my xtable.

2) For the most part of my strings, there are too long and they overflow the page on the right. Is there a way (in latex or with xtable command) to specify that I want an automatic linebreak in my table ? Here is an example of what I am trying to do :

<<echo=FALSE,results="asis">>=
  xtab<-data.frame(c(
    "A very very very very very very very very very very very very very very very very very very very very very very very long string that could be so much longer",
    "Another very very very very very very very very very very very very very very very very very very very very very very very long string"))
  print.xtable(xtab)
@

PS : I can't use {tabular} directly because my data (sentences) depends of a shiny app user's inputs earlier, so I can't know how many of them I have when I write the .rnw file.

These are two independent problems.

Problem 1: Accents not visible.

Solution: Encode the document in UTF-8 and add (at least) \\usepackage[utf8]{inputenc} to the preamble, see eg Wikibooks: Special Characters .

Problem 2: Wrap lines in table.

Solution: Use a paragraph column type ( p , m or b , see here ). For example, p{5cm} produces a column with a width of 5cm with text wrap. The align argument of xtable allows to specify such a column type:

print.xtable(xtable(xtab, align = c("l", "p{5cm}"))) # row names aligned left, second column 5cm wide

Full code (forgive my abuse of accents; it's just for demonstration):

\documentclass{article}
\usepackage[utf8]{inputenc}
\begin{document}

<<echo=FALSE,results="asis">>=
library(xtable)
xtab <- data.frame(Text = c(
  "A vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry long string that could be so much longer",
  "Another vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry vèry long string"))
  print.xtable(xtable(xtab, align = c("l", "p{5cm}")))
@

\end{document}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM