print_md in huxtable changes table formatting

350 views Asked by At

I am using the huxtable package to create tables in a PDF rendered in bookdown. The table is formatted exactly the way I want it, up until I run the print_md command, after which a border is moved up row from underneath the column names to underneath the header. Also, the header is moved from a centered position to right-aligned. Check it out:

df <- data.frame(
  "colname1" = c("something indicator"),
  "colname2" = "[Something](http://www.overleaf.com)",
  "colname3" = "[Something again](http://www.overleaf.com)")

df <- df %>% 
  as_hux() %>%
      theme_basic() %>% 
      set_tb_padding(2)

df <- df %>% 
  set_contents(1, 2:3, c("colname2", "colname3"))  %>% 
  insert_row("", "Header", "Header", after = 0) %>% 
  merge_cells(1, 2:3) %>% 
  set_align(1, everywhere, "center") %>% 
  set_tb_padding(1, everywhere, 0) %>%
  set_bold(1, everywhere)
df

Which gives: enter image description here

Table is formatted correctly. But. You'll notice that the URLs are not formatted correctly. It should only be showing the part within the brackets, which when clicked will take you to the site in parentheses.

This can be remedied with the following code:

df %>% print_md() 

Which gives: enter image description here

Now the URLs look like they should, but the border has erroneously moved up a row, and "Header" is now right-aligned instead of center-aligned. How do I stop that from happening?

1

There are 1 answers

2
mvanaman On

Don't ask me why it works. But changing print_md() to set_markdown() fixed both the border and alignment problems.

EDIT: I'm adding @dash2's comment to this answer.

The reason print_md() was causing problems is because it converts the table to markdown format, which R Markdown then reads and produces a table from. So some features (alignment) get lost in translation. It'd be better to print the table in the intended output format, be it Latex, HTML or whatever you're using, instead of markdown.

But the cells with markdown hyperlinks need to be respected still - print_md() is just the wrong way to go about it. Instead, use set_markdown(). This will ensure that, within huxtable itself, cells with markdown code are interpreted as markdown before the table is printed. The printed table will then retain the intended format.

Thank you @dash2 for creating such a powerful package!