R - Processing cut intervals of the form [x, y] in tables when converting to LaTeX

I am working on a document in R, with knitr for pdflatex and using the extended version of toLatex from memisc.

When I create a table with cut intervals, the square brackets are not sanitized, and pdflatex job errors due to the existence of [ .

I tried putting sanitize=TRUE in chitr code, but this only works for tikz.

I used to use gsub and replaced the string in the R object itself, which is rather inelegant. I hope someone can point me in the direction of the nuance of memisc or knitr, which I do not have, or another function / method that can easily cope with special latex characters.

Example

 library("memisc") library("Hmisc") example<-data.frame(cbind(x=1:100,y=1:100)) example$x<-cut2(example$x,m=20) toLatex(example) 

UPDATE

SO Search I found a post about using latexTranslate with the apply function, but this requires characters, so I would need to separate from factor to character.

I found another SO post that identifies the knitr:::escape_latex , however the piece then outputs the material as markup instead of translating (using results = 'asis') or creating an R-style table inside the code block (using results =' markup). I tried to configure it as a hook function in my parent document, and this led to the output of the entire contents of the document as markup. This is a completely new area for me, so I probably implemented it incorrectly.

 <<setup,include=FALSE>>= hook_inline = knit_hooks$get('inline') knit_hooks$set(inline = function(x) { if (is.character(x)) x = knitr:::escape_latex(x) hook_inline(x) }) @ ... <<tab-example,echo=FALSE,cache=TRUE,results='asis',sanitize=TRUE,inline=TRUE>>= library("Hmisc") library("memisc") example<-data.frame(cbind(x=1:100,y=1:100)) example$x<-cut2(example$x,m=20) toLatex(example) @ 

According to @yihui, this is the wrong way

UPDATE 2

I created a gsub shell that will exit percentages, etc., however [the symbol still pushes latex into math and error mode.

+4
source share
1 answer

Provided by people on tex SE, and [immediately after a line break (\\) is considered an entrance to the mathematical mode. It is very simple to prevent this behavior by adding {} to the output immediately before a [ . My function looks like this:

 escapedLatex<-function (df = NULL) { require("memisc") gsub(gsub(x = toLatex(df, show.xvar = TRUE), pattern = "%", replacement = "\\%", fixed = TRUE), pattern = "[", replacement = "{}[", fixed = TRUE) } 

I would be very happy to see any alternative, more elegant solutions and leave them open for several days.

+2
source

Source: https://habr.com/ru/post/1492511/


All Articles