代码之家  ›  专栏  ›  技术社区  ›  robertspierre

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

  •  0
  • robertspierre  · 技术社区  · 4 年前

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

    特别是我有这个数据帧

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

    我需要 ds 在一个 data.frame 格式。

    我想要的输出是 数据帧 行名为“Min.”、“1st Qu”、“Median”等,列名为“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
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   akrun    4 年前

    我们可以用 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