四舍五入汇总函数导致错误

Rounding summarize function results in error

正在尝试使用 rockchalk 包中的 summarize 输出汇总统计信息。 希望统计数据四舍五入到小数点后两位。我收到一条错误消息 在 summarize.

上使用 round
library(rockchalk)
M1 <- structure(c(0.18, 0.2, 0.24, 0.35, -0.22, -0.17, 0.28, -0.28, -0.14, 0.03, 0.87, -0.2, 0.06, -0.1, -0.72, 0.18, 0.01, 0.31, -0.36, 0.61, -0.16, -0.07, -0.13, 0.01, -0.09, 0.26, -0.14, 0.08, -0.62, -0.2, 0.3, -0.21, -0.11, 0.05, 0.06, -0.28, -0.27, 0.17, 0.42, -0.05, -0.15, 0.05, -0.07, -0.22, -0.34, 0.16, 0.34, 0.1, -0.12, 0.24, 0.45, 0.37, 0.61, 0.9, -0.25, 0.02), .Dim = c(56L, 1L))

#This works
round(apply(M1, 2, mean),2)

#This works
summaryround <- function(x) {round(summary(x),2)} 
apply(M1, 2, summaryround)

#This gives error "non-numeric argument"
round(apply(M1, 2, summarize),2)

#Thought this would work but also gives error "non-numeric argument"
summarizeround <- function(x) {round(summarize(x),2)} 
apply(M1, 2, summarizeround)

有什么想法吗?我可以舍入 summary 的输出但想使用 summarize 如果可能的话,因为我喜欢在同一个打印输出中获得峰度和偏度的输出(当然,可以创建我自己的函数,结合 summarykurtosis 以及我想要的任何东西,而不是如果可以避免的话)。


编辑:实际上应该在大型数据框架上提到 运行;将它变成一个 1 列矩阵,因为我认为这会使可重现的示例更简单。

?rockchalk::summarize 说参数是一个数据框。所以,让M1成为一个数据框

M1<-as.data.frame(M1)
summarize(M1)

$numerics
              V1
0%       -0.7200
25%      -0.1625
50%       0.0150
75%       0.2400
100%      0.9000
mean      0.0400
sd        0.3152
var       0.0993
skewness  0.4485
kurtosis  0.5626
NA's      0.0000
N        56.0000

$factors
NULL

并进行四舍五入

> round(summarize(M1)[[1]],2)
            V1
0%       -0.72
25%      -0.16
50%       0.02
75%       0.24
100%      0.90
mean      0.04
sd        0.32
var       0.10
skewness  0.45
kurtosis  0.56
NA's      0.00
N        56.00

您只需从 summarize 结果中提取 numerics 字段。此外,我更愿意使用 lapply 来保留结果的行名,如果要汇总多个列,则使用 do.call(bind,...)

summarizeround <- function(x) {round(summarize(x)$numerics,2)} 
summaryDf <- do.call(cbind, lapply(as.data.frame(M1), summarizeround))

             x
0%       -0.72
25%      -0.16
50%       0.02
75%       0.24
100%      0.90
mean      0.04
sd        0.32
var       0.10
skewness  0.45
kurtosis  0.56
NA's      0.00
N        56.00