Max Max - 1 year ago 110
R Question

R: loop matrix sort columns individually for specific rows

I want to sort my Matrix (U) columnwise for the rows, which have the same name. My (very large) matrix looks similar to this:

1 2
1 5 6
1 -4 4
1 6 -2
2 7 -2
2 -2 3

Now I want to loop through the matrix looking for the same rows and then sort the columns which have the same resulting in this matrix:

1 2
1 -4 -2
1 5 4
1 6 6
2 -2 -2
2 7 3

My code until now looks like this:

First step was the row count, which works:

z <- 1
for(i in (1:nrow(U))){
if(row.names(U)[i] != row.names(U)[i-1]){
z = (sum(row.names(U) == row.names(U)[i]))+1}}

Now I wanted to add after the row count a sorting function and I tried this for the first set of rows manually:

x <- 1
for(x in (1:ncol(U))){
U[1:3,x]<- U[, lapply(x:NCOL(U), function(x) U[1:3, x]

However this loop is on the one hand very slow and on the other hand it only fills in the first column correctly

Do you have a recommendation how I could improve my sorting function, while taking into account the performance issues?

EDIT: I guess this was confusing in my first edit. The first "column" of my matrix are the row.names and I have in this example a 5x2 Matrix

Answer Source

Here's an approach which just uses order() first by row name, then by each column in turn. Is this what you're after?

U <- matrix(c(5,6,-4,4,6,-2,7,-2,-2,3), byrow=TRUE, ncol=2, dimnames=list(c(1,1,1,2,2), c(1,2)))

apply(U, 2, function(j) j[order(rownames(U), j)])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download