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
For loops
For loops are most commonly used for iterating over the elements of an object (list, vector, etc.)
for Loops in R:
Here is a for loop example in R.
for(i in 1:10) {
print(i)
}
x <- c("a", "b", "c", "d")
for(i in 1:4) {
print(x[i])
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
>
> x <- c("a", "b", "c", "d")
> for(i in 1:4) {
+ print(x[i])
+ }
[1] "a"
[1] "b"
[1] "c"
[1] "d"
Print out each element of ‘x’.
for(letter in x) {
print(letter)
}
Output:
[1] "a"
[1] "b"
[1] "c"
[1] "d"
For one line loops, the curly braces are not strictly necessary.
for(i in 1:4) print(x[i])
Output:
[1] "a"
[1] "b"
[1] "c"
[1] "d"
Nested for loops in R:
for loops can be nested inside of each other like the below example.
x <- matrix(1:10, 5, 2)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}
Output:
[1] 1
[1] 6
[1] 2
[1] 7
[1] 3
[1] 8
[1] 4
[1] 9
[1] 5
[1] 10