pdf_document renders "^" that aren't usable R code

I'm rendering a PDF document with code that ideally would be copy+paste-able for readers. However, it seems "^" is converted to a similar looking, yet unusable form. For example, rendering the following document

---
output: pdf_document
---

```{r}
2^2

```

and then copy+pasting the code in the rendered code chunk back into R yields:

2ˆ2
> Error: unexpected input in "2ˆ"

This doesn't happen with html_document:

 ---
 output: html_document
 ---
 
```{r}
2^2
```
2^2
> [1] 4

Does anyone have suggestions for how to fix this? Output from xfun::session_info('rmarkdown'):


R version 4.1.0 (2021-05-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042), RStudio 1.5.119

Locale:
  LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
  LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
  LC_TIME=English_United States.1252    

Package version:
  base64enc_0.1.3 digest_0.6.28   evaluate_0.14   fastmap_1.1.0   glue_1.4.2      graphics_4.1.0 
  grDevices_4.1.0 highr_0.9       htmltools_0.5.2 jquerylib_0.1.4 jsonlite_1.7.2  knitr_1.36     
  magrittr_2.0.1  methods_4.1.0   rlang_0.4.12    rmarkdown_2.11  stats_4.1.0     stringi_1.7.5  
  stringr_1.4.0   tinytex_0.34    tools_4.1.0     utils_4.1.0     xfun_0.27       yaml_2.2.1     

Pandoc version: 2.12

PDF document are rendered by being processed by LaTeX. LaTeX will process character a certain way and this could happen.

In general, PDF is not a plain text document like HTML is. So I wouldn't expect code chunk in PDF document produced by LaTeX to be ready for copy pasting. Some of the characters could be processed by LaTeX and changed for typesetting or other.

Thanks for your answer! I'll see if I can tweak the LaTeX output and recompile afterwards, or just switch to HTML.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.