R:计算矩阵中的行均值

标签 r

我有一个看起来像这样的矩阵:

> dput(matrix)
structure(list(0.226984126984127, 0.104133986928105, 0.446807359307359, 
    0.231216931216931, 0.103735527010194, 0.464679487179487, 
    0.223544973544974, 0.108543233082707, 0.430808080808081, 
    0.238095238095238, 0.120502226531638, 0.436919746919747, 
    0.242328042328042, 0.117595073914733, 0.467496392496393, 
    0.23452380952381, 0.115559100902687, 0.426222943722944, 0.231216931216931, 
    0.112887365472505, 0.441438006438006, 0.231878306878307, 
    0.0990079365079365, 0.471089743589744, 0.230952380952381, 
    0.123904761370605, 0.414044844044844, 0.226984126984127, 
    0.111960047176765, 0.435427627927628), .Dim = c(3L, 10L), .Dimnames = list(
    c("misclassification.rate", "type1.error", "type2.error"), 
    NULL))

> matrix
                       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]
misclassification.rate 0.227 0.231 0.224 0.238 0.242 0.235 0.231 0.232 0.231 0.227
type1.error            0.104 0.104 0.109 0.121 0.118 0.116 0.113 0.099 0.124 0.112
type2.error            0.447 0.465 0.431 0.437 0.467 0.426 0.441 0.471 0.414 0.435

我想计算误分类率、type1 和 type2 错误的平均值。我试过 apply(matrix, 1, mean)但这给了我以下错误:
> apply(matrix, 1, mean)
misclassification.rate            type1.error            type2.error 
                    NA                     NA                     NA 
Warning messages:
1: In mean.default(newX[, i], ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(newX[, i], ...) :
  argument is not numeric or logical: returning NA
3: In mean.default(newX[, i], ...) :
  argument is not numeric or logical: returning NA
> 

最佳答案

你有列表项作为矩阵元素,这很麻烦。如 mat是你的矩阵,我们可以看到第一列是一个列表。

str(mat[,1])
# List of 3
#  $ misclassification.rate: num 0.227
#  $ type1.error           : num 0.104
#  $ type2.error           : num 0.447

这可能是调用 *bind() 的结果。后 as.list() .例如,
rbind(as.list(1:5), as.list(20:24), as.list(2:6))
#      [,1] [,2] [,3] [,4] [,5]
# [1,] 1    2    3    4    5   
# [2,] 20   21   22   23   24  
# [3,] 2    3    4    5    6   

这是一个矩阵,但具有作为行和列的列表元素。

如果可以的话,最好在到达这一点之前尝试清除它。如果回不去在代码中修复,可以调整mat成合适的矩阵,然后进行计算。
m <- matrix(unlist(mat), nrow(mat), dimnames = dimnames(mat))
rowMeans(m)
# misclassification.rate            type1.error            type2.error 
#              0.2317725              0.1117829              0.4434934 

现在 m是一个包含数字元素的 3x10 矩阵。或者,您可以将其转换为 10x3 矩阵
apply(mat, 1, unlist)

但最好找出导致它的原因并解决它。

关于R:计算矩阵中的行均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28104782/

相关文章:

r - ggplot2:两个映射有一个图例

r - 为数据框自动生成 roxygen2 文档的最佳方法是什么?

r - 使用 purrr :map() 从不规则列表中提取数据

r - R中的lm()回归的summary()中“残留标准误差”的含义是什么?

r - 从 R 发送电子邮件 - 当 Windows 中的计划脚本失败时

r - 使用 `st_write` 标记 kml 特征

r - 双 for 循环只返回最后一项

R - 重新排序直方图条形 - ggplot2

r - 非发光上下文中的响应式(Reactive)对象绑定(bind)

r - 使用多个 geom 时如何消除 ggplotly 重复的图例条目