Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

melt the lower half matrix in R

Tags:

r

matrix

reshape

How can I melt a lower half triangle plus diagonal matrix ?

11 NA NA  NA  NA
12 22 NA  NA  NA
13 23 33  NA  NA
14 24 34  44  NA
15 25 35  45  55
    A <- t(matrix (c(11,  NA, NA,  NA,  NA, 12, 22, NA,  NA,  NA,
   13, 23, 33,  NA,  NA, 14, 24, 34,  44,  NA,15, 25, 
   35,  45,  55), ncol = 5)) 

 > A
     [,1] [,2] [,3] [,4] [,5]
[1,]   11   NA   NA   NA   NA
[2,]   12   22   NA   NA   NA
[3,]   13   23   33   NA   NA
[4,]   14   24   34   44   NA
[5,]   15   25   35   45   55 

To data.frame in row and col (preserving the following order)

col  row   value 
1     1      11
1     2      12
1     3      13
1     4      14
1     5      15
2     2      22
2     3      23
2     4      24
2     5      25
3     3      33
3     4      34
3     5      35
4     4      44
4     5      45
5     5      55
like image 278
jon Avatar asked Nov 22 '11 03:11

jon


People also ask

What is melt() in R?

Melting in R programming is done to organize the data. It is performed using melt() function which takes dataset and column values that has to be kept constant. Using melt(), dataframe is converted into long format and stretches the data frame. Syntax: melt(data, na.rm = FALSE, value.name = “value”)

How do you turn a matrix into a lower triangle?

To convert given matrix into the lower triangular matrix, loop through the matrix and set the values of the element to zero where column number is greater than row number.

What library is melt in R?

The melt function is to be found in the reshape package. If you do not have that package installed, then you will need to install it with install. packages("reshape") before you can use it. Then, when the package is installed, make it available with library(reshape) .

What does upper tri do in R?

tri() function in R Language is used to return a matrix of logical values with upper triangle as TRUE.


1 Answers

If you want the indices as columns as well, this should work:

m <- matrix(1:25,5,5)
m[upper.tri(m)] <- NA
m

     [,1] [,2] [,3] [,4] [,5]
[1,]    1   NA   NA   NA   NA
[2,]    2    7   NA   NA   NA
[3,]    3    8   13   NA   NA
[4,]    4    9   14   19   NA
[5,]    5   10   15   20   25

cbind(which(!is.na(m),arr.ind = TRUE),na.omit(as.vector(m)))
      row col   
 [1,]   1   1  1
 [2,]   2   1  2
 [3,]   3   1  3
 [4,]   4   1  4
 [5,]   5   1  5
 [6,]   2   2  7
 [7,]   3   2  8
 [8,]   4   2  9
 [9,]   5   2 10
[10,]   3   3 13
[11,]   4   3 14
[12,]   5   3 15
[13,]   4   4 19
[14,]   5   4 20
[15,]   5   5 25

I guess I'll explain this a bit. I'm using three "tricks":

  1. The arr.ind argument to which to get the indices
  2. The very useful na.omit function to avoid some extra typing
  3. The fact that R stores matrices in column major form, hence as.vector returns the values in the right order.
like image 73
joran Avatar answered Oct 02 '22 23:10

joran