[R] How to replace all non-maximum values in a row with 0
Owe Jessen
list at econinfo.de
Fri Apr 9 11:08:22 CEST 2010
Am 09.04.2010 10:04, schrieb burgundy:
> 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!
>
Nice little homework to get the day started. :-)
This worked for me, but is probably not the shortest possible answer
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)
nr <- nrow(A)
nc <- ncol(A)
B <- matrix(0,nrow=nr, ncol=nc)
for(i in 1:nr){
x <- which(A[i,]==max(A[i,]))
B[i,x] <- 1
if(sum(B[i,])>1) B[i,] <- as.vector(rep(0,nc))
}
--
Owe Jessen
Nettelbeckstr. 5
24105 Kiel
post at owejessen.de
http://privat.owejessen.de
More information about the R-help
mailing list