R语言adist函数异常输出:为何output不是1×1矩阵?
问题解析:为什么
diag()返回0×0矩阵而非1×1矩阵? 先看你执行的代码及对应输出:
dist <- adist("errors", "eror", costs = c(1, 1, 1), counts = T) dist
输出结果:
[,1] [1,] 2 attr(,"counts") , , ins [,1] [1,] 0 , , del [,1] [1,] 2 , , sub [,1] [1,] 0 attr(,"trafos") [,1] [1,] "MDMMMD"
但运行以下代码时,得到的却是0×0矩阵:
output <- diag(attr(dist, which = "counts")[ , , "ins"]) # 或 [ , , 1] output
输出:
<0 x 0 matrix>
原因拆解
问题出在两个关键环节:
1. 数组自动降维
当你从三维数组attr(dist, "counts")中提取单个切片[,, "ins"]时,R默认启用drop=TRUE参数——它会把原本1×1的二维矩阵结构直接降级成一个标量(既不是矩阵也不是向量,dim属性为NULL)。你可以用代码验证:
counts_ins <- attr(dist, "counts")[,, "ins"] is.matrix(counts_ins) # 返回 FALSE dim(counts_ins) # 返回 NULL
2. diag()函数的行为逻辑
diag()的处理逻辑分三种情况:
- 传入矩阵:返回该矩阵的对角线元素;
- 传入向量:生成以向量元素为对角线的方阵;
- 传入标量n:
- 若n是正整数,生成n×n的单位矩阵;
- 若n是0,生成0×0的空矩阵。
这里你传入的是标量0,所以diag(0)按照规则返回了0×0矩阵,而非你预期的1×1矩阵。
解决办法
如果要得到1×1矩阵的对角线结果,只需在提取数组时关闭自动降维,添加drop=FALSE参数:
output <- diag(attr(dist, "counts")[,, "ins", drop=FALSE]) output
输出:
[,1] [1,] 0
如果只是需要获取那个数值,更简单的方式是直接提取,不用调用diag():
output <- attr(dist, "counts")[,, "ins"] # 输出:0
内容的提问来源于stack exchange,提问作者Julien
相关产品推荐
相关产品推荐

