如何将运行在data.frame上的摘要转换为data.frame本身?我需要一个data.frame作为针织品的输出::kable in RMarkdown。
特别是我有这个数据
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.“、”1 Qu.“、”中位数“等作为行名、"a”和"b“作为列名,以及单元格中的数字。
as.data.frame不工作:
ds.df <- as.data.frame(ds)
print(ds.df)
# Output is messed up这个related question中的代码也不起作用:
df.df2 <- data.frame(unclass(summary(ds.df)), check.names = FALSE, stringsAsFactors = FALSE)
print(df.df2)
# Output equally messed up不推荐表上的broom::tidy,并且无论如何返回一个错误:
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发布于 2021-05-23 00:14:39
我们可以用matrix路线
out <- as.data.frame.matrix(ds)
row.names(out) <- NULL-output
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))-output
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.0https://stackoverflow.com/questions/67655132
复制相似问题