R Markdown 中的汇总统计表

问题描述 投票:0回答:1

如何在 R Markdown 中使用 .pdf 输出制作漂亮的汇总统计表?

我正在尝试这个解决方案

as.data.frame(lapply(df, summary))
,如here所示,但出现以下错误:
Error in dimnames(x) <- dnx : 'dimnames' applied to non-array

所需的输出将类似于不同的统计数据作为行名称,不同的变量作为列名称。转置也很好(实际上甚至更好,但我认为它更难)。 (1 个变量,平均值 + 标准差)示例:

变量
意思是
标清 西格玛
r r-markdown
1个回答
0
投票

您可以在尝试转换为数据框之前创建一个向量。

names(mtcars) |> 
  lapply(
    \(column_name) {
      summary(mtcars[[column_name]]) |>
        as.vector() |> 
        as.data.frame() |>
        setNames(column_name)
    }
  ) |> 
  Reduce(
    f = \(x, y) cbind(x, y),
    x = _,  
    init = data.frame(
      stat = c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", "Max.")
    )
  )
#>      stat      mpg    cyl     disp       hp     drat      wt     qsec     vs
#> 1    Min. 10.40000 4.0000  71.1000  52.0000 2.760000 1.51300 14.50000 0.0000
#> 2 1st Qu. 15.42500 4.0000 120.8250  96.5000 3.080000 2.58125 16.89250 0.0000
#> 3  Median 19.20000 6.0000 196.3000 123.0000 3.695000 3.32500 17.71000 0.0000
#> 4    Mean 20.09062 6.1875 230.7219 146.6875 3.596563 3.21725 17.84875 0.4375
#> 5 3rd Qu. 22.80000 8.0000 326.0000 180.0000 3.920000 3.61000 18.90000 1.0000
#> 6    Max. 33.90000 8.0000 472.0000 335.0000 4.930000 5.42400 22.90000 1.0000
#>        am   gear   carb
#> 1 0.00000 3.0000 1.0000
#> 2 0.00000 3.0000 2.0000
#> 3 0.00000 4.0000 2.0000
#> 4 0.40625 3.6875 2.8125
#> 5 1.00000 4.0000 4.0000
#> 6 1.00000 5.0000 8.0000

创建于 2024-04-12,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.