0

Using Rmarkdown to generate a PDF. I'm bringing in lengthy text strings generated from a prior function to use as grouped row labels in a table. The normal kableExtra::group_rows method works fine. Since I have the same number of rows in each group, I'd like to use the index method, but that doesn't seem to work:

---
output: 
  pdf_document:
    latex_engine: xelatex
    fig_caption: true
---
```{r}
library(magrittr)
library(knitr)
library(kableExtra)

# Build some data
df <- data.frame(x=1:12, y=13:24, z=25:36)

# Row grouping text gets generated from a separate function
gtext <- c("Group 1: text that I don't want to write out",
           "Group 2: because it gets generated from something else",
           "Group 3: so let's make life easy")

# This works fine:
df %>%
  kable(format="latex", booktabs = TRUE, row.names=FALSE) %>%
  group_rows(gtext[1],1,4) %>%
  group_rows(gtext[2],5,8) %>%
  group_rows(gtext[3],9,12)

# But this doesn't:
df %>%
  kable(format="latex", booktabs = TRUE, row.names=FALSE) %>%
  group_rows(index=c(gtext[1]=4,
                     gtext[2]=4,
                     gtext[3]=4))
```

I get the following error upon knitting: "Error in parse(text = x, srcfile = src) : :23:30: unexpected '=' 22:"

Over the course of 40+ tables with some that have up to 10 row groupings, it's easy to see how the index method would save time and prevent errors. Added functionality here (or a workaround that I may have missed) would be most excellent!

bcarothers
  • 824
  • 8
  • 19

1 Answers1

2

I could render this document to html by using

group_rows(index=setNames(c(4, 4, 4), gtext))

The issue appears to be the way you are attempting to create the named vector for the index argument. If you try this in the console, you'll get an error:

c(gtext[1] = 4, gtext[2] = 4, gtext[3] = 4)

While this does not:

setNames(c(4, 4, 4), gtext)
#>           Group 1: text that I don't want to write out 
#>                                                      4 
#> Group 2: because it gets generated from something else 
#>                                                      4 
#>                       Group 3: so let's make life easy 
#>                                                      4
markdly
  • 4,394
  • 2
  • 19
  • 27