简体   繁体   中英

Problem with raw latex output in R Markdown from python function

I want to use R Markdown in combination with python and LaTeX. I've found the module to_latex to convert a Pandas DataFrame to raw LaTeX code. This works really fine in Python. When I try this in Markdown I get some error messages like Undefined control sequence. l.146 \textbackslash Undefined control sequence. l.146 \textbackslash . When I look into my tex-file there is some strange code, indeed. The table from the first five rows and columns of mtcars looks like the following:

`\textbackslash begin\{tabular\}\{llrrrr\}\n\textbackslash toprule\n{}
\& model \& mpg \& cyl \& disp \& hp
\textbackslash\textbackslash{}\n\textbackslash midrule\n0 \& Mazda RX4
\& 21.0 \& 6 \& 160.0 \& 110 \textbackslash\textbackslash{}\n1 \& Mazda
RX4 Wag \& 21.0 \& 6 \& 160.0 \& 110 \textbackslash\textbackslash{}\n2
\& Datsun 710 \& 22.8 \& 4 \& 108.0 \& 93
\textbackslash\textbackslash{}\n3 \& Hornet 4 Drive \& 21.4 \& 6 \&
258.0 \& 110 \textbackslash\textbackslash{}\n4 \& Hornet Sportabout \&
18.7 \& 8 \& 360.0 \& 175
\textbackslash\textbackslash{}\n\textbackslash bottomrule\n\textbackslash end\{tabular\}\n'

So there are these '\textbackslashs' that should not be there, there should be normal backslashs, LaTeX trys to escape them, I guess. Can I prevent this anyhow? My whole rmd script looks like this:

---
title: "Test"
author: "TobiSonne"
date: "5/17/2021"
output: 
  pdf_document:
    number_sections: true
lang: de
fontsize: 12pt
header-includes: 
  - \usepackage{float}
  - \pagenumbering{gobble}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  fig.height = 4,
  fig.width = 7,
  echo = TRUE,
  fig.align  = "center",
  fig.pos = "H",
  out.extra = "", 
  warning = FALSE,
  message = FALSE)
library(reticulate)
```

```{python}
import pandas as pd
```

```{python}
Data = pd.read_csv("mtcars.csv").iloc[0:5, 0:5]
```

```{python, results = "asis"}
Data.to_latex()
```

OK, I have a solution: In the YAML one has to add \usepackage{booktabs} and the last chunk must be:

```{python, results = "asis"}
print(Data.to_latex(escape = False))
```

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