Use an object instead of a string in pack_rows

I'm using kableExtra package to make tables. Inside pack_rows(), I wanted to use an object that I set outside pack_rows() as the group index.

Here is an reproducible example:

This is an option, where you manually set the group index as "Mazda Cars"

library(kableExtra)
dt <- mtcars[1:5, 1:6]

kbl(dt) %>%
  kable_paper("striped", full_width = F) %>%
    pack_rows(index = c("Mazda Cars" = 2,
                      "Other Cars" = 3
  ))

However, I tried creating an object that contains "Mazda Cars", but the table group index shows "group_1" instead of Mazda

dt <- mtcars[1:5, 1:6]
group_1 <- "Mazda"

kbl(dt) %>%
  kable_paper("striped", full_width = F) %>%
  pack_rows(index = c(group_1 = 2,
                      "Other Cars" = 3
  ))

I believe this has something to do with interpretation of vector names, but I don't quite remember what.

Help much appreciated,

Thank you.

Correct.

> (group_1)
[1] "Mazda"
> group_1 = 2
> group_1
[1] 2

This can be somewhat isolated with

suppressPackageStartupMessages({library(dplyr)
  library(kableExtra)})
dt <- mtcars[1:5, 1:6]

the_vector <- c(2,3)
the_vector
names(the_vector) <- c("Mazda","Other Cars")
the_vector

kbl(dt) %>%
  kable_paper("striped", full_width = F) %>%
  pack_rows(index = the_vector)

(snippet won't reprex)

Suggest reposting as function to create named vector to draw a wider audience while I chew on it.

1 Like

I chose an alternative solution.

I used the group_label parameter instead of index parameter inside pack_rows and thus wrote multiple lines of pack_rows(), as seen on the kableExtra vignette

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.