td17
td17

Reputation: 15

Rmarkdown render function: issue with displaying dataframe when converting RMD to HTML

RMarkdown render() function splits each row entry into multiple rows while converting RMD file into html. How can I force it to display each entry on the same row? There is apparently enough space, no need to split....

For example:

Current output:
##                    mpg cyl  disp  hp drat    wt  qsec vs am gear carb mpg2
## Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.0
## Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.0
## Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 22.8
##                   mpg3 mpg4 mpg5
## Mazda RX4         21.0 21.0 21.0
## Mazda RX4 Wag     21.0 21.0 21.0
## Datsun 710        22.8 22.8 22.8

Goal:
##                    mpg cyl  disp  hp drat    wt  qsec vs am gear carb mpg2 mpg3 mpg4 mpg5
## Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.0 21.0 21.0 21.0
## Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.0 21.0 21.0 21.0
## Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 22.8 22.8 22.8 22.8

Code:

mtcars$mpg2 <- mtcars$mpg
mtcars$mpg3 <- mtcars$mpg
mtcars$mpg4 <- mtcars$mpg
mtcars$mpg5 <- mtcars$mpg

print(head(mtcars, 10))
rmarkdown::render("..../testRMD.Rmd")

Thanks for the help!

Upvotes: 0

Views: 160

Answers (1)

Gainz
Gainz

Reputation: 1771

I'm not sure why this is doing this with base R code. But I get it to work with knitr and kableExtra. Maybe this can help you a little bit.

The kable() function is really useful when using tables in markdown (for HTML and even LaTeX's pdf). If you plan to use tables and markdown a lot, I definitively recommend you to take a look at those packages and functions.

Add in setup :

library(knitr)
library(kableExtra)

Then add to your r chunk :

kable(head(mtcars, 10)) %>%
  kable_styling(bootstrap_options = "striped", full_width = F, position = "left")

Note that the table will be a lot nicer with kable (not sure you need/want it).

Here is an example of a possible output on a HTML page: https://i.sstatic.net/PdH10.png

Hope this can help you.

Upvotes: 1

Related Questions