Reputation: 651
I have a matrix containing three columns in R. The matrix could look something like this:
A=matrix(c(1,2,3,4,0.5,1,7,1.2,3,4,2,1),nrow=4, ncol=3)
I want to create a matrix based on A, which in each row of A returns a 1 for the highest value in that row and zero otherwise. So in the specific case above, I need a matrix that looks like this:
B=matrix(c(0,0,0,1,0,0,1,0,1,1,0,0),nrow=4,ncol=3)
I have tried to search the forum, but couldn't find a proper answer.
Thanks.
Upvotes: 3
Views: 197
Reputation: 1919
The below is pretty much the same as Ananda's answer, but the small changes could make a difference in terms of speed if your A is sufficiently large
> A<-matrix(rnorm(1000*1000),nrow=1000)
> system.time(t(apply(A, 1, function(x) as.numeric(x == max(x)))))
user system elapsed
0.117 0.024 0.141
> system.time(1*(A==apply(A,1,max)))
user system elapsed
0.056 0.008 0.065
Upvotes: 5
Reputation: 193677
Perhaps something like this?
t(apply(A, 1, function(x) as.numeric(x == max(x))))
# [,1] [,2] [,3]
# [1,] 0 0 1
# [2,] 0 0 1
# [3,] 0 1 0
# [4,] 1 0 0
Note that in the case of multiple values matching the maximum in a row, there may be more than one "1" per row.
Upvotes: 5