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

Time:07-09

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.

CodePudding user response:

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

CodePudding user response:

You could introduce a space every N number of characters using gsub(), which will work in HTML outputs. If you are printing to Latex, introduce a new line \n instead. The following introduces a space every 10 characters.

iris$Species = as.character(iris$Species)

long <- 'long string, fff,ffdfdfd,ffdfdfd,dfdfdfdfd,ffdfssdfdafdfa,fdfdafdfds,daffdfafdfds,affdaffdsa,fdfasfsafa,adfdafsaf,aaaaaaaaaaalloooonnnng'

iris[1, ]$Species = gsub('(?=(?:.{10}) $)', " ", long, perl = TRUE)

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