Search code examples
rvariablesmatrixvector

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). For example, if I have a matrix, 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:

> 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. 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.


Solution

  • You can do this with 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()). What's your use case?