R Programming
- Overview of R
- Installing R on Windows
- Download and Install RStudio on Windows
- Setting Your Working Directory (Windows)
- Getting Help with R
- Installing R Packages
- Loading R Packages
- Take Input and Print in R
- R Objects and Attributes
- R Data Structures
- R – Operators
- Vectorization
- Dates and Times
- Data Summary
- Reading and Writing Data to and from R
- Control Structure
- Loop Functions
- Functions
- Data Frames and dplyr Package
- Generating Random Numbers
- Random Number Seed in R
- Random Sampling
- Data Visualization Using R
While loops
While loops begin by testing a condition. If it is true, then they execute the loop body. Once the loop body is executed, the condition is tested again, and so forth, until the condition is false, after which the loop exits.
Syntax of while loop:
while (condition)
{
R Code
}
count <- 0
while(count < 10) {
print(count)
count <- count + 1
}
Output:
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
Another Example:
z <- 8
set.seed(1) #set.seed() is used for reproducible results.
while(z >= 6 && z <= 10){
coin <- rbinom(1, 1, 0.5)
if(coin == 1) {
print("It is head")
z <- z + 1
} else {
print("It is tail")
z <- z - 1
}
}
Output:
[1] "It is tail"
[1] "It is tail"
[1] "It is head"
[1] "It is head"
[1] "It is tail"
[1] "It is head"
[1] "It is head"
[1] "It is head"
[1] "It is head"