当前位置: 首页 > 工具软件 > IndexR > 使用案例 >

R中的循环

段干靖
2023-12-01

Most of the time in programming, we need to perform the same operations upon all elements in a vector or perform the same set of actions multiple times. Loop statements in programming are designed for this purpose. R supports two kinds of loops namely the for loop and the while loop. This article elucidates the structure and usage of for loop for programming.

在编程的大多数时间里,我们需要对向量中的所有元素执行相同的操作或多次执行相同的操作集。 编程中的循环语句就是为此目的而设计的。 R支持两种循环,即for循环和while循环。 本文阐明了用于编程的for循环的结构和用法。

R中for循环的结构 (Structure of for loop in R)

The general structure of for loop in R is as follows.

R中for循环的一般结构如下。


for(index in range or vector){
#Write the code to repeat here
}
  • The value index is the indicator of how many times we want the loop to run.

    值索引是我们希望循环运行多少次的指标。
  • The range sets the upper bound on the number of times the loop runs. This number of times is known as iterations in computer science.

    该范围设置循环运行次数的上限。 此iterations在计算机科学中被称为iterations
  • The actions that we need to carry out multiple times is placed between the braces. This can be anything we choose.

    我们需要多次执行的动作放在花括号之间。 这可以是我们选择的任何东西。

We now illustrate the running of a for-loop using simple print statements first.

现在,我们首先使用简单的打印语句来说明for循环的运行。

简单的R for循环示例 (Simple R for loop example)


for(index in 1:5){
  print("Begin loop")
  print(index)
  print("End loop")
}
  • The variable index is a temporary variable that does not need to be defined or initialized outside the loop.

    变量index是一个临时变量,不需要在循环外定义或初始化。
  • At its first occurrence, the index gets set to the starting value or the range, which is here set as 1 to 5. So index value is initially 1.

    第一次出现时, index将设置为起始值或范围,此处将其设置为1到5。因此index值最初为1。
  • With each run of the loop, the value of index is incremented by 1, until it reaches the upper limit 5.

    每次循环运行时,index的值都会增加1,直到达到上限5。
  • Let us now see how the output looks for this loop.

    现在让我们看看输出如何查找此循环。

Output:

输出:


[1] "Begin loop"
[1] 1
[1] "End loop"
[1] "Begin loop"
[1] 2
[1] "End loop"
[1] "Begin loop"
[1] 3
[1] "End loop"
[1] "Begin loop"
[1] 4
[1] "End loop"
[1] "Begin loop"
[1] 5
[1] "End loop"
> 

Notice how the sentinel print statements we placed at the beginning and end of the loop run for each and every iteration, as long as the index value is less than or equal to 5.

请注意,只要索引值小于或等于5,我们在循环的开始和结束处放置的哨兵打印语句将对每个迭代运行。

在向量中使用for循环 (Using for loop in R with vectors)

For loop can also be used to loop over elements in a vector in R. Recall that a vector is defined by using c(element1,element2...) format.

For循环还可以用于在R中向量中的元素之间循环。回想一下,向量是使用c(element1,element2...)格式定义的。

Let us look at a for loop that reads and displays each element in a vector.

让我们看一下一个for循环 ,该循环读取并显示向量中的每个元素。


vec <- c(2,5,6,1,7,8,9)
 for(val in vec){
   print(val)
 }

Output:

输出:


[1] 2
[1] 5
[1] 6
[1] 1
[1] 7
[1] 8
[1] 9

The variable val gets the value of each element in the vector progressively with each iteration and displays it inside the loop’s body. This will prove an important feature when we handle larger data structures in future, which we will see as we go on.

变量val随每次迭代逐步获取向量中每个元素的值,并将其显示在循环体内。 当我们将来处理更大的数据结构时,这将被证明是一个重要的功能,随着我们的不断发展,我们将看到这一点。

嵌套在R中的循环 (Nested for loops in R)

For a vector of one dimension like the one above, it is enough for one looping variable. However, when we are working with multidimensional vectors, say like matrices, we would need one variable for each dimension. Keeping one index constant, we can loop over all the subdimensions of the matrix/vector. This can be illustrated in the following example.

对于一维向量,如上面的维,对于一个循环变量就足够了。 但是,当我们处理多维向量(例如矩阵)时,每个维度都需要一个变量。 保持一个索引不变,我们可以遍历矩阵/向量的所有子维度。 在下面的示例中可以对此进行说明。


for(i in 1:4){
  for(j in 1:3){
    print(i*j)
  }
  cat("\n")
}

We are looping over two variables here. Firstly, for i value 1, the inner loop runs from j value 1 to j value 3. Each time, a product if i and j is printed. Next, i value gets incremented to 2 and j runs from 1 to 3 again. This continues until the i value is exhausted.

我们在这里遍历两个变量 。 首先,对于i值1,内部循环从j值1到j值3进行。每次打印ij的乘积。 接下来, i值增加到2,j再次从1到3。 这一直持续到i值用尽为止。

The line cat("\n") is to just place a new line between each cycle of the inner loop executions for our easy understanding.

cat("\n")行仅在内部循环执行的每个循环之间放置一条新行,以方便我们理解。

Let us now look at the output of this loop.

现在让我们看一下该循环的输出。

Output:

输出:


[1] 1
[1] 2
[1] 3

[1] 2
[1] 4
[1] 6

[1] 3
[1] 6
[1] 9

[1] 4
[1] 8
[1] 12

Similar nesting of loops is used to handle matrix dimensions in R, which we will discuss in the matrices in R tutorial.

类似的循环嵌套用于处理R中的矩阵维,我们将在R教程的矩阵中进行讨论。

翻译自: https://www.journaldev.com/34732/for-loop-in-r

 类似资料: