<分区>
不敢相信我以前从未在 R 中注意到这一点!
如果我转置一个向量,它不会像我期望的那样给出单列矩阵。
示例
test <- c(1, 2, 3, 4)
t(test)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
这在我的一个功能中造成了问题。
有什么解决方法吗?
标签 r
<分区>
不敢相信我以前从未在 R 中注意到这一点!
如果我转置一个向量,它不会像我期望的那样给出单列矩阵。
示例
test <- c(1, 2, 3, 4)
t(test)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
这在我的一个功能中造成了问题。
有什么解决方法吗?
最佳答案
我们用 matrix
包装,默认情况下它给出一个列
matrix(test)
# [,1]
#[1,] 1
#[2,] 2
#[3,] 3
#[4,] 4
正如 ?matrix
的文档所说
If one of nrow or ncol is not given, an attempt is made to infer it from the length of data and the other parameter. If neither is given, a one-column matrix is returned.
此外,matrix
是一个具有dim
属性的vector
,因此,另一种选择是分配dim
属性
dim(test) <- c(length(test), 1)
t
ranspose之所以这样做是根据?t
When x is a vector, it is treated as a column, i.e., the result is a 1-row matrix.
关于r - 将向量转置为单列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199028/