[R] filling the matrix row by row in the order from lower to larger elements

Rui Barradas rui1174 at sapo.pt
Sat Apr 7 01:02:59 CEST 2012


Hello,

Oops!

What happened to the function 'f'?
Forgot to copy and pasted only the rest, now complete.


f <- function(x){
	nr <- nrow(x)
	result <- matrix(0, nrow=nr, ncol=ncol(x))
	colnames(result) <- colnames(x)

	inp.ord <- order(x)[1:nr] - 1 # Keep only one per row, must be zero based
	inx <- cbind(1:nr, inp.ord %/% nr + 1) # Index matrix
	result[inx] <- 100
	result
}

# Original example
input <- as.matrix(data.frame(a=c(5,1,3,7), b=c(2,6,4,8)))
(input)
desired.result <- as.matrix(data.frame(a=c(100,0,100,0), b=c(0,100,0,100)))
(desired.result)
all.equal(f(input), desired.result)

# Two other examples
set.seed(123)
(x <- matrix(sample(10, 10), ncol=2))
f(x)

(y <- matrix(sample(40, 40), ncol=5))
f(y)

Note that there's no loops (or apply, which is also a loop.)

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/filling-the-matrix-row-by-row-in-the-order-from-lower-to-larger-elements-tp4538171p4538486.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list