Martin
Martin

Reputation: 848

show str(...) as table in R Markdown

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 ...

Upvotes: 7

Views: 4467

Answers (2)

R. Schifini
R. Schifini

Reputation: 9313

Try this:

m = sapply(mtcars, typeof)

Result:

> m
     mpg      cyl     disp       hp     drat       wt     qsec       vs       am     gear     carb 
"double" "double" "double" "double" "double" "double" "double" "double" "double" "double" "double" 

Or with lapply:

m = data.frame(lapply(mtcars, typeof))

Result:

> m
     mpg    cyl   disp     hp   drat     wt   qsec     vs     am   gear   carb
1 double double double double double double double double double double double

Upvotes: 2

scoa
scoa

Reputation: 19857

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                         |

Upvotes: 12

Related Questions