for loop in r

To create a for loop in R, you need to specify the start point, the end point and an increment (optional) value. Once the loop is executed, each value between the start point and end point will be processed one at a time.

Here's an example of a for loop that iterates through a sequence of numbers and prints each value:

main.r
for (i in 1:5) {
  print(i)
}
30 chars
4 lines

Output:

main.r
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
30 chars
6 lines

In the above example, i starts from 1 and increments by 1 up to 5. The loop body executes once for each value of i.

You can iterate through other objects as well such as a vector or a list. Here's an example of a for loop that iterates through a list of names and prints each name:

main.r
names_list <- list("John", "Mike", "James")

for (name in names_list) {
  print(name)
} 
89 chars
6 lines

Output:

main.r
[1] "John"
[1] "Mike"
[1] "James"
34 chars
4 lines

In the above example, name takes values from the names_list list one at a time, and the loop body prints each value.

gistlibby LogSnag