需要减少矩阵直到只剩下一个元素。在我有一个 2x2 矩阵之前,这一切都很好。当我从 2x2 矩阵中删除一行或一列时,我最终得到的是一个向量,而不是得到 1x2 或 2x1 矩阵,并且我的代码崩溃了。
测试用例:
# 2x2 matrix. remove row and column to get 1x1 matrix
testm <- matrix( data=0, nrow=2, ncol=2, dimnames=list(c("A","B"),c("A","B")))
print(testm)
print(is.matrix(testm)) # TRUE
testm <- testm[-1,] # should result in 1x2 matrix
print(testm) # vector
print(is.matrix(testm)) # FALSE
testm <- testm[,-1] # error
print(testm)
最佳答案
尝试
testm <- testm[-1,,drop=FALSE]
关于r - 防止 R 将矩阵降级为向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899706/