Search code examples
rkableextra

kableExtra define width/wrap does not work when content is a long string without space?


I would like to wrap a column with a long string however this only seem to work if the content are separated by space. For example:

iris$Species = as.character(iris$Species  )
iris[1, ]$Species = 'long string, fff,ffdfdfd,ffdfdfd,dfdfdfdfd,ffdfssdfdafdfa,fdfdafdfds,daffdfafdfds,affdaffdsa,fdfasfsafa,adfdafsaf,aaaaaaaaaaalloooonnnng'

kbl( iris , format = "html" , row.names = F, caption = "test",
) %>% 
  kable_paper(full_width= FALSE, position = "center")  %>%
  column_spec(5, width = "20px", background = "grey")

so for because row 1, col 5 is one long string the field would just extend outwards and not wrap.

Is there a way around this? thanks in advance.


Solution

  • You could replace the commas with breaks

    iris$Species = as.character(iris$Species  )
    iris[1, ]$Species = 'long string, fff,ffdfdfd,ffdfdfd,dfdfdfdfd,ffdfssdfdafdfa,fdfdafdfds,daffdfafdfds,affdaffdsa,fdfasfsafa,adfdafsaf,aaaaaaaaaaalloooonnnng'
    
    irisNew <- iris %>% 
      mutate(Species = str_replace_all(Species, ',', '<br>'))
    
    kbl( irisNew , format = "html" , row.names = F, caption = "test", escape = F
    ) %>% 
      kable_paper(full_width= FALSE, position = "center")  %>%
      column_spec(5, width = "20px", background = "grey")
    

    sample

    Or use the Zero Width Space unicode character

    irisNew <- iris %>% 
      mutate(Species = str_replace_all(Species, ',', '&#8203;'))
    
    kbl( irisNew , format = "html" , row.names = F, caption = "test", escape = F
    ) %>% 
      kable_paper(full_width= FALSE, position = "center")  %>%
      column_spec(5, width = "20px", background = "grey")
    
    

    sample2