R 中的 IF、ELSE、ELSE IF 语句
if else 语句
对于试图根据条件返回输出的开发人员来说,if-else 语句是一个很好的工具。在 R 中,语法为:
if (condition) { Expr1 } else { Expr2 }
我们要检查存储为“数量”的变量是否大于 20。如果数量大于 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 之间。如果是,那么这品脱就是平均日产量。如果数量 > 30,我们会打印“今天真是好日子!”,否则“今天不够”。
您可以尝试改变数量。
# 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:
根据购买的产品,增值税有不同的税率。假设我们有三种不同的产品,适用不同的增值税:
分类 | 产品 | 增值税 |
---|---|---|
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