Arrange elements on a matrix according to rowSums + short 'apply' Q

Greetings,

My goal is to create a Markov transition matrix (probability of moving from one state to another) with the 'highest traffic' portion of the matrix occupying the top-left section. Consider the following sample:

inputData <- c(
    c(5, 3, 1, 6, 7),
    c(9, 7, 3, 10, 11),
    c(1, 2, 3, 4, 5),
    c(2, 4, 6, 8, 10),
    c(9, 5, 2, 1, 1)
    )

MAT <- matrix(inputData, nrow = 5, ncol = 5, byrow = TRUE)
colnames(MAT) <- c("A", "B", "C", "D", "E")
rownames(MAT) <- c("A", "B", "C", "D", "E")

rowSums(MAT)

I wan to re-arrange the elements of this matrix such that the elements with the largest row sums are placed to the top-left, in descending order. Does this make sense? In this case the order I'm looking for would be B, D, A, E, C Any thoughts?

As an aside, here is the function I've written to construct the transition matrix. Is there a more elegant way to do this that doesn't involve a double transpose?

TMAT <- apply(t(MAT), 2, function(X) X/sum(X))
TMAT <- t(TMAT)

I tried the following:

TMAT <- apply(MAT, 1, function(X) X/sum(X))

But my the custom function is still getting applied over the columns of the array, rather than the rows. For a check try:

rowSums(TMAT)
colSums(TMAT)

Row sums here should equal 1...

Many thanks in advance, Aaron

Answers


Use rowSums and colSums more! The first problem can be done with simple:

MAT[order(rowSums(MAT),decreasing=T),]

The second with:

MAT/rep(rowSums(MAT),nrow(MAT))

this is a bit hacky, but becomes obvious if you recall that matrix is also a by-column vector. Taking also recycling into account it can be also done just by:

MAT/rowSums(MAT)

For your first request, this gets the desired descending reordering by row sums:

MAT[rev(order(rowSums(MAT))), ]

And this gets your TMAT in one step. The apply function returns a series of vectors and the column major ordering of matrices will transpose the results from what beginning users of R expect.

> TMAT <- t(apply(MAT, 1, function(X) X/sum(X)) )
> rowSums(TMAT)
A B C D E 
1 1 1 1 1 

Need Your Help

Capture Image while Device is Locked with Password

android android-intent android-camera android-canvas android-camera-intent

I want to implement a functionality to capture image through front camera when someone tries to unlock my device and enter incorrect password 3 times. I checked that it is possible in Android and s...

Create a small 'window-form' application that runs anywhere

windows linux osx programming-languages widget

I work in the embedded world, using mainly C and no GUI at all (because there is no display screen).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.