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

From: Lars Bishop <lars52r_at_gmail.com>
Date: Tue, 26 Apr 2011 10:48:11 -0400

Thanks a lot to all of you!

On Tue, Apr 26, 2011 at 10:34 AM, Peter Ehlers <ehlers_at_ucalgary.ca> wrote:

> On 2011-04-26 05:26, Dimitris Rizopoulos wrote:
>
>> one way is the following:
>>
>> a<- matrix(rnorm(9), 3 ,3)
>>
>> aa<- a[order(row(a), -a)]
>> matrix(aa, nrow(a), byrow = TRUE)[, 2]
>>
>
> That's clever, Dmitris. And very fast!
>
> carefully. You asked for more _efficient_ and
> I just thought 'shorter code'. I should know
> that whenver I think 'apply', I should think
> 'matrix'.
>
> Peter Ehlers
>
>
>
>>
>> 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
>>>
>>> Lars.
>>>
>>> [[alternative HTML version deleted]]
>>>
>>> ______________________________________________
>>> R-help_at_r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>> http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html>
>>> and provide commented, minimal, self-contained, reproducible code.
>>>
>>>
>>
>

[[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. Received on Tue 26 Apr 2011 - 14:50:15 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 - 15:20:33 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.