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:
... or that:
But I am trying to do this:
source to share
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
.
source to share
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', ' ', gsub('^(\\s*)\\S.*', '\\1', df$Species)), gsub('^\\s*(\\S.*)', '\\1', df$Species))
If df$Species <- " versicolor"
, the result is:" versicolor"
If df$Species <- " one two three"
, the result is:" one two three"
Or, reformatted for clarity:
x <- df$Species
paste0( # Combine edited text
gsub('\\s', ' ', # Replace leading spaces
gsub('^(\\s*)\\S.*', '\\1', x) # Extract leading spaces
),
gsub('^\\s*(\\S.*)', '\\1', x) # Extract trailing text
)
source to share
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))
source to share