[英]Convert an M by N matrix to an array of M vectors each of length N
Trivial question I imagine.. 我想像的琐碎问题
I have an M by N matrix. 我有一个M x N矩阵。 For example:
例如:
mat <- matrix(data = rnorm(12), nrow = 3, ncol = 4)
and I would like to convert it to an array of M vectors each of length N (meaning an array where each of the vectors is a row in the matrix). 我想将其转换为长度为N的M个向量的数组(表示每个向量是矩阵中的一行的数组)。
I'm going to go with @joran and also presume that you mean you want a list, and not an array. 我将使用@joran并假设您的意思是您想要一个列表,而不是一个数组。 So to split a matrix by its rows, you can use
split
with row
因此,要按行拆分矩阵,可以使用按
row
split
split(mat, row(mat))
# $`1`
# [1] 0.4583610 -2.2781416 -1.5936889 0.6746935
#
# $`2`
# [1] 1.3758054 0.3980531 1.0167698 -0.7905586
#
# $`3`
# [1] 1.3177040 -1.5425623 0.2905337 0.4275807
Similarly, to split by the columns you can do split(mat, col(mat))
同样,要按列拆分,可以执行
split(mat, col(mat))
Are you looking for t
to transpose your matrix? 您是否正在寻找
t
来转置矩阵?
mat <- matrix(data = rnorm(12), nrow = 3, ncol = 4)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0.9577888 -0.6362354 -0.02213621 -0.1537499
#[2,] 2.2317189 -0.2593682 0.67468979 -2.2123352
#[3,] 0.8379689 -0.3452324 0.66811564 -1.9828007
t(mat)
# [,1] [,2] [,3]
#[1,] 0.95778884 2.2317189 0.8379689
#[2,] -0.63623540 -0.2593682 -0.3452324
#[3,] -0.02213621 0.6746898 0.6681156
#[4,] -0.15374989 -2.2123352 -1.9828007
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.