From: Christos Hatzis <christos_at_nuverabio.com>

Date: Tue 09 Jan 2007 - 21:39:47 GMT

R-help@stat.math.ethz.ch 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 Wed Jan 10 08:46:48 2007

Date: Tue 09 Jan 2007 - 21:39:47 GMT

Thanks, Marc.

This is what I was trying to do but could not get it to work.

-Christos

-----Original Message-----

From: Marc Schwartz [mailto:marc_schwartz@comcast.net]
Sent: Tuesday, January 09, 2007 4:32 PM

To: christos@nuverabio.com

Cc: 'R-help'

Subject: Re: [R] A vectorization question

On Tue, 2007-01-09 at 16:10 -0500, Christos Hatzis wrote:

*> Hi,
**>
*

> A function calculates the absolute difference between the two largest

*> values of each row of a matrix, as shown in the following example code:
**>
**> cx <- matrix(runif(15),5)
**> cy <- t( apply(cx, 1, order, decreasing=TRUE) )
**>
**> cz <- rep(0, nrow(cx))
**> for( i in 1:nrow(cx) ) cz[i] <- abs(diff(cx[i, cy[i,1:2]]))
**>
**> Anybody has any ideas on how the last loop can be vectorized?
**>
**> Thanks.
*

How about this:

> mat <- matrix(sample(1:50, 12), ncol = 4)

*> mat
*

[,1] [,2] [,3] [,4]

[1,] 39 1 22 11 [2,] 34 28 13 48 [3,] 25 40 38 3

> apply(mat, 1, function(x) abs(diff(sort(x, decreasing = TRUE)[1:2])))

[1] 17 14 2

Or

> apply(mat, 1, function(x) diff(sort(x)[3:4]))

[1] 17 14 2

**HTH,
**
Marc Schwartz

R-help@stat.math.ethz.ch 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 Wed Jan 10 08:46:48 2007

Archive maintained by Robert King, hosted by
the discipline of
statistics at the
University of Newcastle,
Australia.

Archive generated by hypermail 2.1.8, at Tue 09 Jan 2007 - 22:30:26 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.
*