show str(...) as table in R Markdown
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 |
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