How to write a for loop in the R language?
In R language, you can use a for loop to repeatedly execute a block of code. The basic syntax of a for loop is as follows:
for (variable in sequence) {
# 执行的代码
}
A variable is used to store each element of the sequence, which can be a vector, list, or other iterable object.
Here is an example using a for loop to calculate and output the square of numbers 1 to 5.
for (i in 1:5) {
square <- i^2
print(square)
}
The output result is:
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
In each iteration, the variable i takes on the values 1, 2, 3, 4, and 5 respectively. Calculate the square of i and assign the result to the variable square, then use the print() function to output the result.
Additionally, you can utilize other control flow statements such as break and next to manage the execution of the loop.