R语言中的循环

Project Euler01
Problem 2, Even Fibonacci numbers

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

400万以内的偶数斐波那契数列求和

1
2
3
4
5
6
7
8
9
10
x[1] <- 1
x[2] <- 2
for (i in 3:1000){
x[i]=x[i-1] +f[i-2]
if (x[i] > 4000000){
break
}
}
x <- x[-i]
sum(x[x %% 2 == 0])

结果4613732
但是我并不知道x[i] > 4000000时i是多少,看了别人的答案可以使用while解决这个问题

1
2
3
4
5
6
7
8
i <- 2
x <- 1:2
while (x[i] < 4e6) {
x[i+1] <- x[i-1] + x[i]
i <- i + 1
}
x <- x[-i]
sum(x[x %% 2 == 0])

看了一下r-bloggers上别人的答案
发现还可以用repeat这个命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fibonacci <- numeric()
fibonacci[1] <- 1
fibonacci[2] <- 2
i <- 3
repeat {
fibonacci[i] <- fibonacci[i-1] + fibonacci[i-2]
if (fibonacci[i] > 4e6) break
i <- i + 1
}
# calculate the sum
fibonacci <- fibonacci[-length(fibonacci)] # remove the last term
flag <- fibonacci %% 2 == 0 # find the indexes of even numbers
result <- sum(fibonacci[flag])
cat("The result is:", result, "\n")

现在有两个问题
1.repeat和while有什么区别?
2.R语言中的循环有多少种?
for,while,repeat,向量化操作,apply,自己写的函数也算。
这里有一份来自Datacamp的Tutorials十分值得阅读,价值250美元,很长很全面,但是很好懂
A Tutorial on Loops in R - Usage and Alternatives

------ 本文结束------