Monday, 26 August 2013

Local and Global variables in R. How can I change the value of the argument used in the 'for' loop?

Local and Global variables in R. How can I change the value of the
argument used in the 'for' loop?

Using the combination of for and while, my problem is similar to this
example: I want to add 1 to the first element of the vector x, skip
elements 2:4 and add 1 to the fifth element until to the end of the vector
x.
j <- 0
x <- c(rep(1, 4), 5:7)
for (i in 1:length(x)){
x[i] <- x[i] + 1
while (j == 0){
i <- i + 1
if(x[i] != 1) j <- 1
print(paste('in:', i))
}
print(paste('out:', i))
}
the result shows that the i value do not change. Is it possible to change
it in R?
[1] "in: 2"
[1] "in: 3"
[1] "in: 4"
[1] "in: 5"
[1] "out: 5" # look!!!
[1] "out: 2"
[1] "out: 3"
[1] "out: 4"
[1] "out: 5"
[1] "out: 6"
[1] "out: 7"

No comments:

Post a Comment