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


greetings,

my goal create markov transition matrix (probability of moving 1 state another) 'highest traffic' portion of matrix occupying top-left section. consider 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 re-arrange elements of matrix such elements largest row sums placed top-left, in descending order. make sense? in case order i'm looking b, d, a, e, c thoughts?

as aside, here function i've written construct transition matrix. there more elegant way doesn't involve double transpose?

tmat <- apply(t(mat), 2, function(x) x/sum(x)) tmat <- t(tmat) 

i tried following:

tmat <- apply(mat, 1, function(x) x/sum(x)) 

but custom function still getting applied on columns of array, rather rows. check try:

rowsums(tmat) colsums(tmat) 

row sums here should equal 1...

many in advance, aaron

use rowsums , colsums more!
first problem can done simple:

mat[order(rowsums(mat),decreasing=t),] 

the second with:

mat/rep(rowsums(mat),nrow(mat)) 

this bit hacky, becomes obvious if recall matrix by-column vector. taking recycling account can done by:

mat/rowsums(mat) 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -