[R] reshape non-square matrix

Rolf Turner r.turner at auckland.ac.nz
Sat Mar 1 06:44:27 CET 2014


On 01/03/14 14:49, Chirag Gupta wrote:

> Hi list
>
> I have a matrix of size m x n (m and n are different, hence non square!)
> I want to melt it in such a way that I get a df of 3 columns. m ,n

    Surely you mean i, j (i = 1, ..., m), j = 1, ..., n).

> and cell
> value in the original matrix.

Yes:

dfX <- data.frame(i=as.vector(row(X)),j=as.vector(col(X)),
                   value=as.vector(X))

where X is your matrix.  The fact that X is non-square is of course 
completely irrelevant.

cheers,

Rolf Turner




More information about the R-help mailing list