[R] Second largest element from each matrix row

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Apr 26 14:26:51 CEST 2011


one way is the following:

a <- matrix(rnorm(9), 3 ,3)

aa <- a[order(row(a), -a)]
matrix(aa, nrow(a), byrow = TRUE)[, 2]


I hope it helps.

Best,
Dimitris


On 4/26/2011 2:01 PM, Lars Bishop wrote:
> Hi,
>
> I need to extract the second largest element from each row of a
> matrix. Below is my solution, but I think there should be a more efficient
> way to accomplish the same, or not?
>
>
>   set.seed(1)
>   a<- matrix(rnorm(9), 3 ,3)
>   sec.large<- as.vector(apply(a, 1, order, decreasing=T)[2,])
>   ans<- sapply(1:length(sec.large), function(i) a[i, sec.large[i]])
>   ans
>
> Thanks in advance for your help,
> Lars.
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list