首页 文章

舍入汇总函数导致错误

提问于
浏览
0

尝试使用 rockchalk 包中的 summarize 输出汇总统计信息 . 希望统计数据四舍五入为2位小数 . 在 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列矩阵,因为我认为这将使可重现的例子更简单 .

2 回答

  • 2

    您只需要从 summarize 结果中提取 numerics 字段 . 此外,我更喜欢使用 lapply 来保留结果的rownames并使用 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
    
  • 0

    ?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
    

相关问题