Re: [R] 'for' loop, two variables

From: Benno Pütz <puetz_at_mpipsykl.mpg.de>
Date: Tue, 29 Jul 2008 14:21:17 +0200

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)



R-help_at_r-project.org 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 Tue 29 Jul 2008 - 12:26:10 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 29 Jul 2008 - 12:32:51 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.

list of date sections of archive