[R] 'for' loop, two variables

Duncan Murdoch murdoch at stats.uwo.ca
Tue Jul 29 14:09:29 CEST 2008


On 7/29/2008 7:55 AM, Oehler, Friderike (AGPP) wrote:
> Dear Rusers,
> I am still an unexperienced builder of functions and loops, so my question is
> very basic: Is it possible to introduce a second variable (j) into my loop.
> To examplify:
> 
> # This works fine:
> fn <- function (x) {if (x>46 & x<52) 1 else 0}    
> res <-NULL 
> for (i in 40:60) res <-c(res,fn(i))
> res
> 
> # But here, there is an error in the "for" expression:
> fn <- function (x,y) {if (x>46 & x<52 & y<12) 1 else 0 }    
> res <-NULL 
> for (i in 40:60 & j in 0:20) res <-c(res,fn(i,j)) 
> # How do I have to write the expression "i in 40:60 & j in 0:20"? Or is there
> no way to do that, i.e. I have to do the calculation in two steps?

You need two steps.  You probably want either

for (i in 40:60) for (j in 0:20) res <-c(res,fn(i,j))

or

i <- 40:60
j <- 0:20
for (ind in seq_along(i)) res <- c(res, fn(i[ind], j[ind]))

(which do quite different loops).

Duncan Murdoch



More information about the R-help mailing list