How to use texreg for a long table in RMarkdown

I recently posted a question asking how to create a long table using Stargazer in RMarkdown. I haven't found a solution but in looking did find another package with similar functionality and a "longtable" option, but it also isn't working in RMarkdown (or at least I'm not sure how to get it to work). Below is an example that more-or-less reproduces the problem. Note that the "tv_short" model works fine, but the "tv_long" does not compile.

I'm hoping a solution using this package might be more straightforward. If not, would anyone mind offering advice on how to ask a better question, or an alternative place to ask? The problem is a barrier to creating a reproducible document, so I greatly appreciate any help or feedback.

---
title: ""
header-includes:
   - \usepackage{longtable}
output:
      bookdown::pdf_document2:
        toc: no
        keep_tex: false
---

```{r, include=FALSE}
library(forcats) # for the gss_cat dataset
library(texreg) # to format the table

tv_short <- lm(tvhours ~ marital + age,
               data = gss_cat)

tv_long <- lm(tvhours ~ marital + age + race + rincome + partyid + relig + denom,
              data = gss_cat)

```

```{r, results='asis', echo = FALSE}

texreg(tv_long,
       longtable = TRUE,
       use.packages = FALSE)

```

It is possible you get an error because gss_cat contains a column with income description which contains $ which is a special character in LaTeX. It seems texreg won't escape special char for you so you need to do it.
For example using

gss_cat2 <- gss_cat %>%
  mutate(rincome = stringr::str_replace_all(rincome, "[$]", "\\\\$"))

Rmd would be like this

---
title: ""
header-includes:
   - \usepackage{longtable}
output:
  bookdown::pdf_document2:
    toc: no
    keep_tex: true
    keep_md: true
---

```{r, include=FALSE}
library(forcats) # for the gss_cat dataset
library(texreg) # to format the table
library(dplyr)

gss_cat2 <- gss_cat %>%
  mutate(rincome = stringr::str_replace_all(rincome, "[$]", "\\\\$"))

tv_short <- lm(tvhours ~ marital + age,
               data = gss_cat2)

tv_long <- lm(tvhours ~ marital + age + race + rincome + partyid + relig + denom,
              data = gss_cat2)

```

```{r, results='asis', echo = FALSE}
texreg(tv_long,
       longtable = TRUE,
       use.packages = FALSE)
```

Hope it helps.

Yes! Thank you so much. I wasn't getting the exact error message I produced with my own data as with the gss_cat data, so I wondered if your solution would work, but it turns out it did! (I also had and income variable with a $ in my data that was apparently muddling things up).

Thank you, thank you.

1 Like

This topic was automatically closed 7 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.