r - Max of row in matrix -
i have matrix containing 3 columns in r. matrix this:
a=matrix(c(1,2,3,4,0.5,1,7,1.2,3,4,2,1),nrow=4, ncol=3)
i want create matrix based on a, in each row of returns 1 highest value in row , 0 otherwise. in specific case above, need matrix looks this:
b=matrix(c(0,0,0,1,0,0,1,0,1,1,0,0),nrow=4,ncol=3)
i have tried search forum, couldn't find proper answer.
thanks.
the below pretty same ananda's answer, small changes make difference in terms of speed if 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
Comments
Post a Comment