Search code examples
rshinyformattingkablekableextra

Do not remove spaces in kable function - with example


I'm summarizing data and creating a table within a Shiny application. My basic problem is that I would like to add some additional spaces in between elements in a concatenated string so that it is more readable, but the spaces added seem to disappear. I think that the paste() function is appropriately adding the extra space around the "+/-" symbol, but that using either kable or kableExtra to create a table deletes the spaces.

I think I'm asking the same question as this person did, but that individual did not provide a full reproducible example. I've attempted to create a reprex below with the iris dataset.

I have three attempts to use mutate() to create a new variable with the "+/-" symbol. My best understanding is that this is not really the problem. I would like to be able to add in any amount of blank spaces on either side of this symbol for readability.

library(tidyverse)
library(kableExtra)


data(iris)


data.summary = iris %>% 
  group_by(Species) %>% 
  summarise(N = n(),
            avg.sepal.width = round(mean(Sepal.Width),2),
            sd.sepal.width = round(sd(Sepal.Width),2)) %>% 
  # mutate(table.name = paste(avg.sepal.width, '\u00B1', sd.sepal.width)) %>% 
  # mutate(table.name = paste(avg.sepal.width, '\u00B1', sd.sepal.width, sep= "    ")) %>% 
  mutate(table.name = paste(avg.sepal.width, '   ', '\u00B1','   ', sd.sepal.width, sep= "    ")) %>% 
  


  knitr::kable(caption = "Iris Avg Sepal Width \u00B1 Standard Deviation ", align = "c") %>%
  kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = F, position = "left") 


data.summary

Here is a screenshot of the resulting table-viewed in RStudio. When using Shiny, the results are the same. No matter how many spaces I add, they all go away when formatted in this table

table screenshot


Solution

  • This is not a kable problem. This is how html behaves. If you want to add extra spaces in text you need to add " " to your text. Make this your paste separator, and ensure you turn escape = FALSE inside kable:

    library(tidyverse)
    library(kableExtra)
    
    data(iris)
    
    data.summary = iris %>% 
      group_by(Species) %>% 
      summarise(N = n(),
                avg.sepal.width = round(mean(Sepal.Width),2),
                sd.sepal.width = round(sd(Sepal.Width),2)) %>% 
      mutate(table.name = paste(avg.sepal.width, '\u00B1', 
                                sd.sepal.width, sep = " ")) %>% 
      knitr::kable(caption = "Iris Avg Sepal Width \u00B1 Standard Deviation ", 
                   align = "c", escape = FALSE) %>%
      kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed"), 
                                full_width = F, 
                                position = "left") 
    
    data.summary
    

    enter image description here