[R] for loop question
Uwe Ligges
ligges at amadeus.statistik.uni-dortmund.de
Tue Sep 11 21:59:59 CEST 2001
"HEUMANN,JOHN (A-Loveland,ex1)" wrote:
>
> In the windows version of R (1.3.0) is the following a bug, a
> known problem, or expected behavior:
>
> > for (i in 1:2) {
> + for (j in i+1:3) {
> + print(j)
> + }
> + }
> [1] 2
> [1] 3
> [1] 4 ????
> [1] 3
> [1] 4 ????
> [1] 5 ????
Looks extremly as expected:
# outer loop i=1
# [1] 2 i=1, j=i+1
# [1] 3 i=1, j=i+2
# [1] 4 i=1, j=i+3
# outer loop i=2
# [1] 3 i=2, j=i+1
# [1] 4 i=2, j=i+2
# [1] 5 i=2, j=i+3
> Conversely, the following behaves as expected:
>
> > for (i in 1:2) {
> + k <- i+1
> + for (j in k:3) {
> + print(j)
> + }
> + }
> [1] 2
> [1] 3
> [1] 3
What you mean is (the braces!!!):
for (i in 1:2) {
for (j in (i+1):3)
print(j)
}
Have a look at this (no spaces are here asn intentional negative
example):
1+1:3 # the sequence is evaluated at first!
Another way to do your calculation:
i <- 1:2
j <- 3
lapply(i, function(x) seq(x+1,j))
Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list