Here we will discuss for loop statements in R and use them in creating simple functions for calculations.
For other statement types for creating algorithms, see the pages on if-else and while loop statements, and creating functions.
For loops are used to performs tasks through iterations for a set range of values.
[1] 2
[1] 3
[1] 4
[1] "The number 2 is even."
[1] "The number 4 is even."
[1] "The number 6 is even."
[1] 2
[1] 5
[1] 4
[1] 10
[1] 6
[1] 15
Here, \(N\) and \(M\) are natural numbers \(1, 2, 3, \ldots\).
To calculate the sum of numbers from N to M:
\[N + (N+1) + \cdots + (M-1) + M\] You can simply use:
For example:
[1] 55
However, we want to show how to do this iteratively by writing a function.
The variables in the equation are the values \(N\) and \(M\).
To create the function, use:
You can then evaluate the sum from \(N=1\) to \(M=10\):
[1] 55
To derive the first \(N\) numbers of the Fibonacci sequence where each term after \(0, 1\) is the sum of the last two terms:
\[0, 1, 1, 2, 3, 5, 8, 13, 21, ...\] The argument is the value \(N = \{1, 2, 3, \ldots\}\).
To create the function, use:
FibN = function(n){
seq = c(0, 1)
for(i in 1:n){
newNum = seq[length(seq)] + seq[length(seq)-1]
seq = c(seq, newNum)
}
return(seq[1:n])
}
For examples, you can then derive the first \(N\) numbers for \(N=1\), \(N=2\), \(N=6\), and \(N=20\):
[1] 0
[1] 0 1
[1] 0 1 1 2 3 5
[1] 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
[16] 610 987 1597 2584 4181
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes