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.

1 What Are For Loop Statements in R

For loops are used to performs tasks through iterations for a set range of values.

For loop statements take the form:

for(range){
  code chunk that specifies task(s) to perform
}

Basic examples:

for(n in 2:4){
  print(n)
}
[1] 2
[1] 3
[1] 4
set = c(2, 4, 6)
for(n in set){
  print(paste("The number", n, "is even."))
}
[1] "The number 2 is even."
[1] "The number 4 is even."
[1] "The number 6 is even."

Nested example:

x = c(1, 2, 3)
y = c(2, 5)
for(a in x){
  for(b in y){
    print(a*b)
  }
}
[1] 2
[1] 5
[1] 4
[1] 10
[1] 6
[1] 15

2 A Function to Sum Up the Numbers from N to M in R

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:

sum(N:M)

For example:

sum(1:10)
[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:

sumNM = function(N, M){
  sum = 0
  for(i in N:M){
    sum = sum + i
  }
  return(sum)
}

You can then evaluate the sum from \(N=1\) to \(M=10\):

sumNM(1, 10)
[1] 55

3 A Function to Derive the First N Numbers in the Fibonacci Sequence in R

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\):

FibN(1)
[1] 0
FibN(2)
[1] 0 1
FibN(6)
[1] 0 1 1 2 3 5
FibN(20)
 [1]    0    1    1    2    3    5    8   13   21   34   55   89  144  233  377
[16]  610  987 1597 2584 4181

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes