R While 循环及编程示例

R 语言中的 While 循环

R 语言中的 While 循环是一个语句,它会持续运行直到 while 块之后的条件得到满足。

R While 循环语法

以下是 R 语言 While 循环的语法

while (condition) {
     Exp	
}

R While 循环流程图

R While Loop Flowchart
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 美元以下,我们将做空。否则,我们将继续持有。每次循环后,价格可能在 50 美元上下波动 -10 到 +10。您可以按以下方式编写代码:

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