R 中的 IF、ELSE、ELSE IF 语句
if else 语句
if-else 语句是开发者根据条件返回输出的一个好工具。在 R 中,语法如下:
if (condition) { Expr1 } else { Expr2 }
我们想检查一个名为“quantity”的变量是否大于 20。如果 quantity 大于 20,代码将打印“您卖了很多!”否则打印“今天的量不够。”
# Create vector quantity quantity <- 25 # Set the is-else statement if (quantity > 20) { print('You sold a lot!') } else { print('Not enough for today') }
输出
## [1] "You sold a lot!"
注意:请确保正确编写缩进。如果缩进位置不正确,包含多个条件的代码会变得难以阅读。
else if 语句
我们可以进一步使用 else if 语句来定制控制级别。使用 elif,您可以添加任意数量的条件。语法如下:
if (condition1) { expr1 } else if (condition2) { expr2 } else if (condition3) { expr3 } else { expr4 }
我们想知道我们是否卖出了 20 到 30 之间的数量。如果卖出了,就打印“普通的一天”。如果 quantity > 30,我们打印“多么美好的一天!”,否则打印“今天的量不够。”
您可以尝试更改 quantity 的数量。
# Create vector quantiy quantity <- 10 # Create multiple condition statement if (quantity <20) { print('Not enough for today') } else if (quantity > 20 &quantity <= 30) { print('Average day') } else { print('What a great day!') }
输出
## [1] "Not enough for today"
示例 2
增值税(VAT)根据购买的产品有不同的税率。想象一下我们有三种不同类型的增值税应用不同的产品
类别 | 产品 | 增值税 |
---|---|---|
A | 书籍、杂志、报纸等。 | 8% |
B | 蔬菜、肉类、饮料等。 | 10% |
C | T恤、牛仔裤、裤子等。 | 20% |
我们可以编写一个链式语句来为顾客购买的产品应用正确的增值税率。
category <- 'A' price <- 10 if (category =='A'){ cat('A vat rate of 8% is applied.','The total price is',price *1.08) } else if (category =='B'){ cat('A vat rate of 10% is applied.','The total price is',price *1.10) } else { cat('A vat rate of 20% is applied.','The total price is',price *1.20) }
输出
# A vat rate of 8% is applied. The total price is 10.8