[英]Vectorizing rows/columns of a Matrix in R
I want to be able to take a matrix in R, and have each row be it's own vector (ideally with a name I can iterate and assign while I loop through the matrix). 我希望能够在R中采用矩阵,并让每一行都是它自己的向量(理想情况下,我在遍历矩阵时可以迭代并指定名称)。 For example, if I have a matrix, M:
例如,如果我有一个矩阵M:
> M<-matrix(c(1,-4,-4,3,4,-4,17,15,-12),3,3)
> M
[,1] [,2] [,3]
[1,] 1 3 17
[2,] -4 4 15
[3,] -4 -4 -12
I would like to be able to go through M and create vectors that I could name so that I end up with each row as it's own, standalone vector: 我希望能够遍历M并创建可以命名的向量,以便最终得到每一行,因为它是自己的独立向量:
> row1<-M[1,];row2<-M[2,];row3<-M[3,];
> row1
[1] 1 3 17
> row2
[1] -4 4 15
> row3
[1] -4 -4 -12
Clearly I can do this going through, but it'd be a nightmare for a matrix with 100+ rows, and I don't know how to iterate a for loop to allow me to do this where the variable name assignment changes on each iterand. 显然,我可以做到这一点,但是对于具有100多行的矩阵,这将是一场噩梦,而且我不知道如何迭代for循环,以允许我在每个iterand变量名称分配发生更改的情况下执行此操作。 Ideally I'd like to be able to do it where I have a matrix with row names, and then I can assign each vector the variable name that is the rowname of it's row in the original matrix.
理想情况下,我希望能够在具有行名的矩阵的情况下执行此操作,然后可以为每个向量分配变量名,该变量名是原始矩阵中该行的行名。
You can do this with assign()
: 您可以使用
assign()
完成此操作:
for (i in 1:nrow(M)) {
vname <- paste0("row",i)
assign(vname,row[i,])
}
or 要么
for (i in rownames(M)) assign(i,M[i,])
... but you should think carefully about why you want to. ...但是您应该仔细考虑为什么要这么做。 If you do this you're going to end up with a namespace cluttered with individual variables.
如果这样做,您将最终得到一个充满各个变量的命名空间。 Furthermore, to access the individual variables in a loop you're then going to have to jump through ugly and inefficient hoops with
get()
(the inverse of assign()
). 此外,要在循环中访问各个变量,您将不得不使用
get()
( assign()
的反函数get()
来跳过难看而效率低下的圈。 What's your use case? 您的用例是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.