是否有用于r-markdown的库或函数将数据帧的结构显示为表格?类似于str(myDataFrame)
的输出但是作为一个相当格式化的r-markdown表?
例如,以下输出应至少显示为包含要素名称的列和数据类型。一些示例值很好,但不是必需的。
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 ...
答案 0 :(得分:9)
str使用cat,因此无法将其转换为漂亮的data.frame进行打印。但你可以模仿它的功能来创建一个,然后将它传递给你最喜欢的rmarkdown表格式化程序(kable,pander等):
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 |
答案 1 :(得分:1)
试试这个:
m = sapply(mtcars, FUN = function(x) typeof(x))
结果:
> m
mpg cyl disp hp drat wt qsec vs am gear carb
"double" "double" "double" "double" "double" "double" "double" "double" "double" "double" "double"
或lapply
:
m = data.frame(lapply(mtcars,FUN = function(x) typeof(x)))
结果:
> m
mpg cyl disp hp drat wt qsec vs am gear carb
1 double double double double double double double double double double double