Here we will discuss while loop statements in R and use them in creating simple functions.

For other statement types for creating algorithms, see the pages on for loop and if-else statements, and creating functions.

1 What Are While Loop Statements in R

While loops are used to performs tasks through iterations while a set of conditions are still satisfied.

While loop statements take the form:

while(condition){
  code chunk that specifies task(s) to perform
}

Basic example:

You can use logical and relational operators to specify conditions.

i = 0
while(i < 3){
  i = i + 1
  print(i)
}
[1] 1
[1] 2
[1] 3

2 A Function to List the Exponents of 2, Less Than or Equal to X in R

Here, an exponent of 2 is a number of the form \(2^n\), for \(n = 0, 1, 2, ...\).

The argument of interest is \(X = \{1, 2, 3. \ldots\}\).

To create the function, run the loop for numbers \(2^n <= X\):

exp2x = function(x){
  n = 0
  explist = c()
  while(2^n <= x){
    explist = c(explist, 2^n)
    n = n + 1
  }
  return(explist)
}

You can then derive the list of exponents for \(X=1\), and \(X=1024\):

exp2x(1)
[1] 1
exp2x(1024)
 [1]    1    2    4    8   16   32   64  128  256  512 1024

3 A Function to Find the First Perfect Square, Greater than X in R

A perfect square is the square of an integer.

The argument of interest is \(X = \{1, 2, 3. \ldots\}\).

To create the function, run the loop while the square root of numbers greater than \(X\) are not round:

perf = function(x){
  n = x + 1
  while(sqrt(n) != round(sqrt(n))){
    n = n + 1
  }
  return(n)
}

You can then derive the first perfect square after \(X=45\), and \(X=100\):

perf(45)
[1] 49
perf(100)
[1] 121

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