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

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Tue, 29 Jul 2008 08:09:29 -0400

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



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:12:56 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