[R] 'for' loop, two variables

Benno Pütz puetz at mpipsykl.mpg.de
Tue Jul 29 14:21:17 CEST 2008


On 29.Jul.2008, at 14:13, ONKELINX, Thierry wrote:

> Dear Frederike,
>
> #Both your functions are vectorized. So you don't need loops. Working
> with vectorized functions is much faster than looping.
>
> fn <- function (x,y) {
>    ifelse(x>46 & x<52 & y<12, 1, 0)
> }
> datagrid <- expand.grid(i = 40:60, j = 0:20)
> res <- apply(datagrid, 1, function(z){
>    fn(z["i"], z["j"])
> })
>

or

outer(40:60,0:20,fn2)

which also keeps the matrix structure ...

(use as.vector(...) or as.vector(t(...)) if you need a vector)



More information about the R-help mailing list