gusa10
gusa10

Reputation: 189

Order lower matrix in R

It would be nice to receive your help.

I have a lower triangle matrix, but I would like to edit the order of the rows, based on my OWN list of names (maybe a vector?).

INPUT

   A   C   D   B
A  0   NA  NA  NA
C  13  0   NA  NA
D  14  17  0   NA
B  12  15  16  0

OUTPUT

  A   B   C   D
A 0   NA  NA  NA
B 12  0   NA  NA
C 13  15  0   NA
D 14  16  17   0

I want to recall the order of the rows should be a list provided by me, and NOT any ascending or descending order.

Thank you for your time!

Upvotes: 0

Views: 206

Answers (1)

akrun
akrun

Reputation: 887098

We can use lower.tri to get a logical matrix where the lower half elements are TRUE and others FALSE, subset the dataset ('v1'). Use this to order (v1[order(v1)]) and assign it back to the lower triangle of the data

v1 <- df1[lower.tri(df1)]
df1[lower.tri(df1)] <- v1[order(v1)]

Upvotes: 1

Related Questions