我有一个看起来像这样的矩阵:
> 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/