简体   繁体   中英

R Stargazer knit to pdf with ampersand (&) in table

I'm trying to knit a stargazer table to pdf in R, and I'm having an issue with an ampersand (&) in one of the cells. I want to keep the ampersand (because it is a business name and affects order).

Here's the code i'm using:

```{r results='asis'}

old_df <-  bus_df %>%
  mutate(char_date = as.character(clean_start_date)) %>% 
  mutate(business_name= str_replace_all(business_name,"&","\\\\&")) %>% 
  select(business_name, char_date) %>%
  slice(1:5) 

old_df %>% 
  stargazer(summary=FALSE, header=FALSE, title="Oldest 5 Busiensses")
```

First row in data:

A & A BUILDING MATERIAL CO | 1921-01-01

Error:

>! Extra alignment tab has been changed to \cr.
><recently read> \endtemplate 
>                             
>l.217 1 & A & A BUILDING MATERIAL CO &
>
>pandoc: Error producing PDF from TeX source
>Error: pandoc document conversion failed with error 43
>Execution halted

I excluded commented out the code that I tried to add escape characters to the ampersand, but any number of slashes (up to 6) returns an error. 1, 3, and 5 breaks the code chunk, while 2, 4, and 6 break the knit. 2 doesn't change the character in the cell (remains &) while 4 and 6 insert the slash ('\\&'), but the slash breaks the knit.

With for slashes:

First row in data:

A \\& A BUILDING MATERIAL CO | 1921-01-01

Error:

>! Extra alignment tab has been changed to \cr.
><recently read> \endtemplate 
>                             
>l.217 ...\textbackslash & A BUILDING MATERIAL CO &
>
>pandoc: Error producing PDF from TeX source
>Error: pandoc document conversion failed with error 43
>Execution halted

Let me know if you need more detail!

Thanks!

While stargazer is great for formatting model output, the xtable package provides the functionality you want for the formatting of data.frames, etc. The code chunk below should do the trick.

```{r results='asis'}

old_df <-  bus_df %>%
  mutate(char_date = as.character(clean_start_date)) %>% 
  select(business_name, char_date) %>%
  slice(1:5) 

xtable(old_df) 

```

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