[R] filling the matrix row by row in the order from lower to larger elements
Dimitri Liakhovitski
dimitri.liakhovitski at gmail.com
Sun Apr 8 16:31:45 CEST 2012
Thank you very much, Rui.
This definitely produces the result needed.
Again, I have not checked the speed yet.
input<-as.matrix(data.frame(a=c(5,1,3,7),b=c(2,6,4,8)))
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
}
f(input)
Dimitri
On Fri, Apr 6, 2012 at 7:02 PM, Rui Barradas <rui1174 at sapo.pt> wrote:
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Dimitri Liakhovitski
marketfusionanalytics.com
More information about the R-help
mailing list