【问题标题】:Using apply function: getting NA values in return as list of values appears non.numeric使用应用函数:获取 NA 值作为返回值列表显示为 non.numeric
【发布时间】:2021-12-22 11:35:46
【问题描述】:

我有一个值列表作为输出:

               [,1]         [,2]         [,3]        
ATE_true      numeric,1000 numeric,1000 numeric,1000
ate_now       numeric,1000 numeric,1000 numeric,1000
ate_truew     numeric,1000 numeric,1000 numeric,1000
ate_estw      numeric,1000 numeric,1000 numeric,1000
ci_w          numeric,1000 numeric,1000 numeric,1000

我想获得每 1000 个值的平均值,即 mean(ATE_true[,1], ATE_true[,2]... 等等。因此使用了 apply 函数

apply(output,1:2,mean)

但我得到返回 NA 值并出现错误: 在 mean.default(newX[, i], ...) 中: 参数不是数字或逻辑:返回 NA

我理解输出是列表格式,它被认为是非数字的,但是我该如何解决这个问题?

我想要的输出:

               [,1]  [,2] [,3]
ATE_true       0.98  0.94 0.97
ate_now        0.86  0.85 0.88
ate_truew      0.83  0.87 0.85
ate_estw       0.86  0.89 0.90
ci_w           0.92  0.91 0.95

【问题讨论】:

    标签: r apply


    【解决方案1】:

    它是一个matrix,元素为list。我们需要lapply/sapply

    sapply(output, mean)
    

    -输出

     [1] -0.046958713 -0.007220200  0.029603442  0.003012857 -0.049690575 -0.027583183  0.013375545  0.008587789  0.010594652  0.019766799
    [11] -0.016020775  0.015412491
    

    如果我们需要数据在matrix,使用dim

    out <- sapply(output, mean)
    dim(out) <- dim(output)
    

    -输出

    > out
                 [,1]         [,2]        [,3]
    [1,] -0.046958713 -0.049690575  0.01059465
    [2,] -0.007220200 -0.027583183  0.01976680
    [3,]  0.029603442  0.013375545 -0.01602077
    [4,]  0.003012857  0.008587789  0.01541249
    

    如果我们也需要dimnames

    dimnames(out) <- dimnames(output)
    

    数据

    set.seed(24)
    output <- matrix(replicate(12, rnorm(1000), simplify = FALSE), 4, 3)
    

    【讨论】:

    • 是的,但是那样我在可视化结果时会遇到问题。最初我有一个大约 40 (8 * 5) 的列表。我已经更新了我希望输出的样子。
    • @TriparnaPoddar 尝试更新
    猜你喜欢
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2020-08-13
    • 2013-11-09
    相关资源
    最近更新 更多