Re: [R] Second largest element from each matrix row

From: David Winsemius <>
Date: Tue, 26 Apr 2011 08:36:11 -0400

On Apr 26, 2011, at 8:01 AM, 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

There are probably many but this one is reasonably compact, one-step, and readable:

 > ans2 <- apply(a, 1, function(i) sort(i)[ dim(a)[2]-1])  > ans2

Refreshing my mail client proves I was right about many solutions, but this is the first (so far) to use the dim attribute.

David Winsemius, MD
West Hartford, CT

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Tue 26 Apr 2011 - 12:38:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 26 Apr 2011 - 16:10:33 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive