Search code examples
pdfkablekableextra

How to have partially italicized columns in pdf output?


This question is related to Creating a data frame that produces partially italicized cells with pkg:sjPlot functions

I'd like to have partially italicized cells in a kable. I have tried

library(tidyverse); library(kableExtra)

sum_dat_final2 <- list(Site = c("Hanauma Bay", "Hanauma Bay", "Hanauma Bay", "Waikiki", "Waikiki", "Waikiki"), 
                   Coral_taxon = expression( italic(Montipora)~ spp., 
                                             italic(Pocillopora)~spp., 
                                             italic(Porites)~spp., 
                                             italic(Montipora)~ spp.,  
                                             italic(Pocillopora)~spp.,  
                                             italic(Porites)~spp.))

sum_dat_final2 %>%
  as.data.frame()%>%
  kbl(longtable = F, "latex")

and got this error Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ‘"expression"’ to a data.frame

Many thanks in advance!!


Solution

  • You may italicize specific parts by adding $. In this sense, you need to set escape = F on your kbl function.

    ```{r}
    library(tidyverse); library(kableExtra)
    
    sum_dat_final2 <- list(Site = c("Hanauma Bay", "Hanauma Bay", "Hanauma Bay", "Waikiki", "Waikiki", "Waikiki"), 
                       "Coral_taxon" = c("$Montipora$$~$ spp.",
                                       "$Pocillopora$$~$spp.",
                                       "$Porites$$~$spp.",
                                       "$Montipora$$~$ spp.",
                                       "$Pocillopora$$~$spp.",
                                       "$Porites$$~$spp."))
    
    sum_dat_final2 %>%
      as.data.frame()%>%
      kbl(longtable = F, "latex", 
          escape = F,
          col.names = c("Site", "Coral taxonomie"))
    ``` 
    

    --output

    enter image description here