'kableExtra: Vertical alignment not working in PDF output with many columns

I would like to align all columns in a kableExtra table to the top. The valign = "top" option does not seem to solve the issue here. Also, the third column is somehow dropped on top of the second for some reason, and citations are not working too.

The MWE below is based on this related SO question, which only needs 2 columns: kable: Vertical alignment does not work with pdf output

For a screenshot of the MWE see here: https://i.stack.imgur.com/RYg4r.jpg

The idea is to use the table later in an Rmd report (using bookdown/huskydown).

   library(knitr)
   library(dplyr)
   library(kableExtra)

   num_obs <- 3
   text_string <- "Lorem ipsum dolor sit amet, vitae, augue aliquam luctus class non. Lectus maecenas ullamcorper commodo ut non maximus eros ad. Mollis rutrum bibendum ut ipsum nisl, mattis placerat, odio. Eu, non morbi nunc mollis." 
   fig_path <- paste0("\\includegraphics[scale=0.5]{uw.png} \\\\")
   fig_paths <- rep(fig_path, num_obs)

   table <- dplyr::tibble(
     col1 = 1:num_obs, 
     col2 = fig_paths,
     col3 = LETTERS[1:num_obs],
     col4 = c("\\href{http://eng.wikipedia.org}{Wiki}", "\\cite{R-base}", "\\cite{R-base}"),
     col5 = c(rep(text_string, num_obs))
   )

   kable(
     table, 
     escape = FALSE, # needed to be able to include latex commands
     format = "latex",  # format = latex, html
     booktabs = T, 
     align = "l",
     valign = "top", ## not working really
   ) %>% 
     kable_styling(full_width = F,
                   font_size = 9,
                   latex_options = c("hold_position")
     ) %>% 
     # row characteristics: set header row bold
     row_spec(row = 0, bold = T) %>%
     # column characteristics: set widths
     column_spec(1, width = "2em") %>% #
     column_spec(2, width = "6em") %>%
     column_spec(3, width = "3em") %>%
     column_spec(4, width = "20em") %>%
     column_spec(5, width = "10em") %>%
     # group rows together and give these groups labels
     pack_rows("Group 1", 1, 1) %>% 
     pack_rows("Group 2", 2, 3)



Solution 1:[1]

\\\\ after \\includegraphics produces a new row after each image, so columns 3, 4, 5 are moved under each image. Just remove \\\\ and add valign = TRUE, i.e.

fig_path <- paste0("\\includegraphics[valign = TRUE, scale = 0.5]{uw.png}")

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1