Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse diagonal on matrix

Tags:

r

matrix

So I have 2 dataframes. picture them like so:

 data1 <- data.frame(c(1.2, 1.4, 1.3),
                     c(1.12,1.1, 1.9),
                     c(1.8, 1.1, 1.32))

 data2 <- data.frame(c(0.4, 0.2, 0.3),
                     c(0.1, 0.1, 0.4),
                     c(0.5, 0.7, 0.4))

how can I create a joint matrix that will look like this:

combined.data
> 1.2  1.12  1.80
  1.4 1.10  0.7
  1.3  0.4  0.4

upper left matrix is data1, lower-right is data2. I'm

So far, my code is this and I get what I want but up-side down:

new <- -data1
#new <- new[, rev(colnames(data1))]
# diag(new) <- NA
corel <- data2
#corel <- corel[, rev(colnames(data2))]


new[upper.tri(new)] <-  corel[upper.tri(corel)]

And I need the rows and column order to be intact

Any thoughts?

After using Haboryme's take, I somehow got the results. And I've generated a heatmap to show it. Problem is that in some spaces, the data are overlapping the 2 matrices.

Here's the heatmap enter image description here

Above the diagonal it needs to be fully red, and below the diagonal, blue.

I've accepted the answer by Haboryme. and the problem was that my data was 32*31. if your matrix is not square it's going to be a mess! I just added 1 dummy column to my dataset and it worked like a charm!

like image 520
Mixalis Avatar asked Feb 03 '17 15:02

Mixalis


1 Answers

You could do:

data1 <- data.frame(c(1.2, 1.4, 1.3),
                    c(1.12,1.1, 1.9),
                    c(1.8, 1.1, 1.32))

data2 <- data.frame(c(0.4, 0.2, 0.3),
                    c(0.1, 0.1, 0.4),
                    c(0.5, 0.7, 0.4))

combined=as.matrix(data1)
combined[apply(lower.tri( as.matrix(data2)), 1, rev)]  <-as.matrix(data2)[apply(lower.tri( as.matrix(data2)), 1, rev)]

> combined
     c.1.2..1.4..1.3. c.1.12..1.1..1.9. c.1.8..1.1..1.32.
[1,]              1.2              1.12               1.8
[2,]              1.4              1.10               0.7
[3,]              1.3              0.40               0.4
like image 90
Haboryme Avatar answered Oct 09 '22 17:10

Haboryme