Is there a library or function for r-markdown to show the structure of a dataframe as a table? Something similar tot the output of str(myDataFrame)
but as a pretty formatted r-markdown table?
For example the following output should be shown as at least the colums holding the feature names, and the datatypes. Some example values would be nice but are not required.
str(mtcars)
'data.frame': 32 obs. of 11 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
$ disp: num 160 160 108 258 360 ...
$ hp : num 110 110 93 110 175 105 245 62 95 123 ...
$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
$ wt : num 2.62 2.88 2.32 3.21 3.44 ...
$ qsec: num 16.5 17 18.6 19.4 17 ...
$ vs : num 0 0 1 1 0 1 0 1 1 1 ...
$ am : num 1 1 1 0 0 0 0 0 0 0 ...
$ gear: num 4 4 4 3 3 3 3 4 4 4 ...
$ carb: num 4 4 1 1 2 1 4 2 2 4 ...
10.1 The function knitr::kable() The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.
If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .
RMarkdown is an extension to markdown which includes the ability to embed code chunks and several other extensions useful for writing technical reports. The rmarkdown package extends the knitr package to, in one step, allow conversion between an RMarkdown file (.Rmd) into PDF, HTML, word document, amongst others.
str uses cat so there is no way to transform it into a pretty data.frame to print. But you can mimic its functionalities to create one, and then pass it to your favorite rmarkdown table formatter (kable, pander, etc.):
library(knitr)
library(magrittr)
data.frame(variable = names(mtcars),
classe = sapply(mtcars, typeof),
first_values = sapply(mtcars, function(x) paste0(head(x), collapse = ", ")),
row.names = NULL) %>%
kable()
|variable |classe |first_values |
|:--------|:-------|:----------------------------------------|
|mpg |numeric |21, 21, 22.8, 21.4, 18.7, 18.1 |
|cyl |numeric |6, 6, 4, 6, 8, 6 |
|disp |numeric |160, 160, 108, 258, 360, 225 |
|hp |numeric |110, 110, 93, 110, 175, 105 |
|drat |numeric |3.9, 3.9, 3.85, 3.08, 3.15, 2.76 |
|wt |numeric |2.62, 2.875, 2.32, 3.215, 3.44, 3.46 |
|qsec |numeric |16.46, 17.02, 18.61, 19.44, 17.02, 20.22 |
|vs |numeric |0, 0, 1, 1, 0, 1 |
|am |numeric |1, 1, 1, 0, 0, 0 |
|gear |numeric |4, 4, 4, 3, 3, 3 |
|carb |numeric |4, 4, 1, 1, 2, 1 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With