[R] Second largest element from each matrix row
santosh.srinivas at gmail.com
Tue Apr 26 14:27:09 CEST 2011
would this work (shorter)?
apply(a, 1, function(x) x[order(x)])
On Tue, Apr 26, 2011 at 5:31 PM, Lars Bishop <lars52r at gmail.com> wrote:
> 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?
> 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]])
> Thanks in advance for your help,
> [[alternative HTML version deleted]]
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help