Hi:

This isn't much shorter than the previous solution, but here's another take,
operating row-wise.

A <- matrix (c(2,  3,  0,  0,  200, 30, 0,  0,  2,  50, 0,  0,  3,  0,  0,
                       0,  0,  8,  8,  0), nrow = 4, byrow=T)

# Write a vector function to apply to each row: begin by initializing a zero
# vector of length = no. columns. Next, find which indices of the row vector
x
# match the maximum. If that number is >1, return a zero vector, else
replace
# the index where the maximum resides to 1.
f <- function(x) {
   o <- rep(0, length(x))
   w <- which(x == max(x))
   r <- if(length(w) > 1) {o} else {
         o[w] <- 1; o}
   r
 }
# Test:
> t(apply(A, 1, f))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    1
[2,]    0    0    0    0    1
[3,]    0    0    1    0    0
[4,]    0    0    0    0    0

HTH,
Dennis

On Fri, Apr 9, 2010 at 1:04 AM, burgundy <saub...@yahoo.com> wrote:

>
> Hi,
>
> I would like to replace all the max values per row with "1" and all other
> values with "0". If there are two max values, then "0" for both. Example:
>
> from:
> 2  3  0  0  200
> 30 0  0  2  50
> 0  0  3  0  0
> 0  0  8  8  0
>
> to:
> 0  0  0  0  1
> 0  0  0  0  1
> 0  0  1  0  0
> 0  0  0  0  0
>
> Thanks!
> --
> View this message in context:
> http://n4.nabble.com/How-to-replace-all-non-maximum-values-in-a-row-with-0-tp1819018p1819018.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@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.
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to