Print your HTML or Word table in knitr to respect line spaces

Using knitr and Rstudio, I am trying to print a dataframe in HTML or Word so that leading spaces in versicolor will move the versicolor to the right.

#data
library(knitr ) 
library(xtable)

df <- iris[c(1,51),c(5,1)]
df$Species  <- as.character(df$Species)
df$Species[ df$Species=="versicolor"]  <- "         versicolor"

      

Try different combinations of kable () ...

#table
kable(  df)
kable(  df, right = FALSE,align = c("l", "l" ) )
kable(  df, right = FALSE,align = c("r", "l" ) )

      

I get this: enter image description here

... or that: enter image description here

But I am trying to do this: enter image description here

+4


source to share


4 answers


If you want to guess with some HTML:

df$Species[ df$Species=="versicolor"]  <- 
  "<code style='background:white'>         </code>versicolor"` will get you something like you want

      

or



df$Species[ df$Species=="versicolor"]  <- 
  "<span style='padding-left:30px'>         versicolor</span>"

      

will give you a space on the left.

The latter might even be in a cleaner programmatic way (by inserting multiples of # in padding-left

.

+3


source


You can try adding

df$Species <- gsub(" ", "&nbsp;", df$Species, fixed=TRUE)

      



before creating a table that will change all your whitespace to versicolor in HTML without breaks.

+3


source


Separate leading spaces from the ending text by one gsub

. Then globally replace those spaces with the second one gsub

. Finally, combine the two pieces with paste

.

As a one-liner:

paste0(gsub('\\s', '&nbsp;', gsub('^(\\s*)\\S.*', '\\1', df$Species)), gsub('^\\s*(\\S.*)', '\\1', df$Species))

      

If df$Species <- " versicolor"

, the result is:"&nbsp;&nbsp;&nbsp;versicolor"

If df$Species <- " one two three"

, the result is:"&nbsp;&nbsp;&nbsp;one two three"

Or, reformatted for clarity:

x <- df$Species

paste0(                                 # Combine edited text
    gsub('\\s', '&nbsp;',               # Replace leading spaces
        gsub('^(\\s*)\\S.*', '\\1', x)  # Extract leading spaces
    ), 
    gsub('^\\s*(\\S.*)', '\\1', x)      # Extract trailing text
)

      

+1


source


How about using the kableExtra package? See "Indenting a Line" here:

https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html

Basically,

library(kableExtra)
dt <- mtcars[1:5, 1:6]
kable(dt) %>%
  kable_styling("striped", full_width = F) %>%
  add_indent(c(1, 3, 5))

      

0


source







All Articles