Display a data frame as table in R Markdown

穿精又带淫゛_ 提交于 2020-01-22 14:12:09

问题


In knitr I want to add a (small) data frame as a table using the kable package:

---
output: html_document
---

```{r}
knitr::kable(mtcars[1:5,1:5], format="html")
```

This returns a compact table as above, while changing it to format="markdown"returns a nice table but spanning the whole page:

I have found the knitr manual but it does not cover the extra formatting options for each format. How can I change the size of a knitr table or even better, where can I get this information from?


回答1:


The general approach would be to use your own custom CSS and include that in the YAML at the start of the document.

You can actually sort of do this from within your document, but I would suggest editing your CSS outside of the document and working from there.

Here's a minimal example:

---
title: "Test"
date: "24 October 2015"
output: 
  html_document:
    css: mystyle.css
---

```{r, results='asis'}
writeLines("td, th { padding : 6px } th { background-color : brown ; color : white; border : 1px solid white; } td { color : brown ; border : 1px solid brown }", con = "mystyle.css")
dset1 <- head(ToothGrowth)
knitr::kable(dset1, format = "html")
```

This should:

  1. Create a file named "mystyle.css" with your relevant CSS styling.
  2. Produce something that looks something like the following.



来源:https://stackoverflow.com/questions/33319457/display-a-data-frame-as-table-in-r-markdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!