[R] Second largest element from each matrix row

peter dalgaard pdalgd at gmail.com
Tue Apr 26 17:13:10 CEST 2011


On Apr 26, 2011, at 14:36 , David Winsemius wrote:

> 
> 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.

Anything with sort() or order() will have complexity O(n*log(n)) or worse (n is the number of columns), whereas finding the k-th largest element has complexity O(k*n). 

For moderate n, this may be unimportant, but you could potentially find a speedup using

sort.int(i, decreasing=TRUE, partial=2)[2]

or

max(i[-which.max(i)])

-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list