[R] Vectorizing a "for" loop

Marc Schwartz (via MN) mschwartz at mn.rr.com
Thu Aug 3 16:23:42 CEST 2006


On Thu, 2006-08-03 at 10:10 -0400, Daniel Gerlanc wrote:
> 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!

See ?outer

> outer(rows, columns, function(x, y) abs(x - y))
     [,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

HTH,

Marc Schwartz



More information about the R-help mailing list