将 data.frame 的摘要转换为数据框

Convert summary of data.frame into a dataframe

如何将 data.frame 上的摘要 运行 转换为 data.frame 本身?我需要一个 data.frame 作为 RMarkdown 中 knitr::kable 的输出。

特别是我有这个数据框

d <- data.frame(a=c(1,2,3), b=c(4,5,6))
ds <- summary(d)
class(ds)
# returns "table"

我需要 ds 格式的 data.frame

我想要的输出是 data.frame,其中“Min.”、“1st Qu.”、“Median”等作为行名,“a”和“b”作为列名, 以及单元格中的数字。

as.data.frame 无效:

ds.df <- as.data.frame(ds)
print(ds.df)
# Output is messed up

中的代码也不起作用:

df.df2 <- data.frame(unclass(summary(ds.df)), check.names = FALSE, stringsAsFactors = FALSE)
print(df.df2)
# Output equally messed up

broom::tidy on a table 已弃用,无论如何 returns 一个错误:

df.df3 <- broom::tidy(ds)
# Returns error
# Error: Columns 1 and 2 must be named.
# Moreover
# 'tidy.table' is deprecated.

as.data.frame.matrix 将“Min”和统计信息的其他名称放在每个单元格中,而不是行名称:

ds.df3 <- as.data.frame.matrix(ds)
print(ds.df3)
# Returns "Min" and "1sd Qu." inside the cell
# instead of them being row names

我们可以使用matrix路线

out <- as.data.frame.matrix(ds)
row.names(out) <- NULL

-输出

out
             a             b
1 Min.   :1.0   Min.   :4.0  
2 1st Qu.:1.5   1st Qu.:4.5  
3 Median :2.0   Median :5.0  
4 Mean   :2.0   Mean   :5.0  
5 3rd Qu.:2.5   3rd Qu.:5.5  
6 Max.   :3.0   Max.   :6.0  

如果我们需要 min 等作为行名,使用 sapply 遍历列并应用 summary

as.data.frame(sapply(d, summary))

-输出

          a   b
Min.    1.0 4.0
1st Qu. 1.5 4.5
Median  2.0 5.0
Mean    2.0 5.0
3rd Qu. 2.5 5.5
Max.    3.0 6.0