Re: [R] Vectorizing a "for" loop

From: Petr Pikal <petr.pikal_at_precheza.cz>
Date: Fri 04 Aug 2006 - 00:24:30 EST


Hi

outer(rows, columns, function(x,y) abs(x-y)) shall do it.

HTH
Petr

On 3 Aug 2006 at 10:10, Daniel Gerlanc wrote:

Date sent:      	Thu, 3 Aug 2006 10:10:46 -0400
From:           	"Daniel Gerlanc" <dgerlanc@gmail.com>
To:             	r-help@stat.math.ethz.ch
Subject:        	[R] Vectorizing a "for" loop
Send reply to:  	dgerlanc@gmail.com
	<mailto:r-help-request@stat.math.ethz.ch?subject=unsubscribe>
	<mailto:r-help-request@stat.math.ethz.ch?subject=subscribe>

> Hello all,
>
> Consider the following problem:
>
> There are two vectors:
>
> rows <- c(1, 2, 3, 4, 5)
> columns <- c(10, 11, 12, 13, 14)
>
> I want to create a matrix with dimensions length(rows) x
> length(columns):
>
> res <- matrix(nrow = length(rows), ncol = length(columns))
>
> If "i" and "j" are the row and column indexes respectively, the values
> of the cells are abs(rows[i] - columns[j]). The resultant matrix
> follows:
>
> [,1] [,2] [,3] [,4] [,5]
> [1,] 9 10 11 12 13
> [2,] 8 9 10 11 12
> [3,] 7 8 9 10 11
> [4,] 6 7 8 9 10
> [5,] 5 6 7 8 9
>
> This matrix may be generated by using a simple "for" loop:
>
> for(i in 1:length(rows)){
> for(j in 1:length(columns)){
> res[i,j] <- abs(rows[i] - columns[j])
> }
> }
>
> Is there a quicker, vector-based approach for doing this or a function
> included in the recommended packages that does this?
>
> Thanks!
>
> -- Dan Gerlanc
> Williams College
>
> ______________________________________________
> 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.

Petr Pikal
petr.pikal@precheza.cz



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 Fri Aug 04 00:47:53 2006

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 Fri 04 Aug 2006 - 02:20:20 EST.

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