R While 循环及其编程示例
R 编程中的 While 循环
R 编程中的 While 循环是一个语句,它会一直运行,直到满足 while 块后的条件为止。
R 中的 While 循环语法
以下是 R 编程中 While 循环的语法:
while (condition) { Exp }
R While 循环流程图

备注:记住在某个时候写一个结束条件,否则循环将无限期地进行下去。
R 编程示例中的 While 循环
例子1
让我们来看一个非常简单的 R编程 示例来理解 while 循环的概念。您将创建一个循环,并在每次运行后将存储的变量加 1。您需要关闭循环,因此我们明确告诉 R 在变量达到 10 时停止循环。
备注:如果要查看当前循环值,则需要将变量包装在函数 print() 内。
#Create a variable with value 1 begin <- 1 #Create the loop while (begin <= 10){ #See which we are cat('This is loop number',begin) #add 1 to the variable begin after each loop begin <- begin+1 print(begin) }
输出:
## This is loop number 1[1] 2 ## This is loop number 2[1] 3 ## This is loop number 3[1] 4 ## This is loop number 4[1] 5 ## This is loop number 5[1] 6 ## This is loop number 6[1] 7 ## This is loop number 7[1] 8 ## This is loop number 8[1] 9 ## This is loop number 9[1] 10 ## This is loop number 10[1] 11
例子2
你以 50 美元的价格购买了一只股票。如果价格跌破 45 美元,我们想卖空它。否则,我们会将其保留在我们的投资组合中。每次循环后,价格可能会在 10 左右波动 -10 到 +50 之间。你可以编写如下代码:
set.seed(123) # Set variable stock and price stock <- 50 price <- 50 # Loop variable counts the number of loops loop <- 1 # Set the while statement while (price > 45){ # Create a random price between 40 and 60 price <- stock + sample(-10:10, 1) # Count the number of loop loop = loop +1 # Print the number of loop print(loop) }
输出:
## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7
cat('it took',loop,'loop before we short the price. The lowest price is',price)
输出:
## it took 7 loop before we short the price. The lowest price is 40