I recently started using the huxtable R package for tables and I'm really impressed with it. One thing I can't seem to figure out, however, is how to get line breaks within a cell. Here's what I've tried
library(tidyverse)
library(huxtable)
cars <- mtcars %>%
mutate(car = rownames(.),
car = str_replace(car, " ", "\n")) %>%
slice(1:5) %>%
select(car, cyl, hp)
cars
# A tibble: 5 x 3
car cyl hp
<chr> <dbl> <dbl>
1 "Mazda\nRX4" 6.00 110
2 "Mazda\nRX4 Wag" 6.00 110
3 "Datsun\n710" 4.00 93.0
4 "Hornet\n4 Drive" 6.00 110
5 "Hornet\nSportabout" 8.00 175
ht <- as_hux(cars, add_colnames = TRUE)
escape_contents(ht) <- TRUE
ht
But this ends up without the line break, as in the screenshot below
The escape_contents
part doesn't seem to make a difference.
I'm not sure if what I want is possible, but I know it is in other packages (e.g., DT::datatable
). I'd really like to use huxtable, if possible, however, because I like the design and flexibility of the package.
Any thoughts would be great.
EDIT: I should have specified I'm hoping to get this to work for PDF.
According to Escaping HTML or LaTeX,
You should use escape_contents(ht) <- FALSE
and use <br>
tag instead of \n
library(tidyverse)
library(huxtable)
cars <- mtcars %>% mutate(car = rownames(.),
car = str_replace(car, " ", "<br>")) %>%
slice(1:5) %>% select(car, cyl, hp)
ht <- as_hux(cars, add_colnames = TRUE)
escape_contents(ht) <- FALSE
ht
note that the output is a Rmarkdown document and thanks for the package information. it looks good. following is the output of mine
Try this, which minimizes the amount of backslashes:
library(tidyverse)
library(huxtable)
cars <- mtcars %>% mutate(car = rownames(.))
cars$car <- str_replace(cars$car, " ", "\\\\newline ")
cars %>%
as_hux(add_colnames = TRUE) %>%
set_wrap(TRUE) %>%
set_escape_contents(everywhere, "car", FALSE) %>%
quick_pdf()
The set_wrap()
call is necessary for LaTeX tables to accept newlines, I believe.
If you want to escape different parts of the cells containing newlines, you can do that manually, e.g. with xtable::sanitize()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With