if-else语句

在R中,if-else语句的语法是:

if (condition) {
    Expr1 
} else {
    Expr2
}

210516_1

例如,想检查变量quantity是否大于20。如果大于20,就输出'You sold a lot!'否则输出'Not enough for today'

quantity <-  25
# 设置is-else 语句
if (quantity > 20) {
    print('You sold a lot!')
} else {
    print('Not enough for today')  
}

Output:

## [1] "You sold a lot!"

注意确保正确地缩进格式。

else if 语句

可以使用else if语句进一步定制控件级别。使用elif,可以添加任意数量的条件。语法是:

if (condition1) { 
    expr1
    } else if (condition2) {
    expr2
    } else if  (condition3) {
    expr3
    } else {
    expr4
}

例如,如果 quantity 在 20-30之间,则输出Average day. 如果 quantity  大于 30 ,则输出 What a great day!, 否则,输出 Not enough for today.

quantity <-  10
# 创建多条件语句
if (quantity <20) {
      print('Not enough for today')
} else if (quantity > 20  &quantity <= 30) {
     print('Average day')
} else {
      print('What a great day!')
}

Output:

## [1] "Not enough for today"

例2:

增值税根据购买的产品有不同的税率。假设我们有三种不同的产品,使用不同的增值税:

CategoriesProductsVAT
ABook, magazine, newspaper, etc..8%
BVegetable, meat, beverage, etc..10%
CTee-shirt, jean, pant, etc..20%

我们可以写一个 chain,对客户购买的产品应用正确的增值税税率。

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)  
}

Output:

# A vat rate of 8% is applied. The total price is 10.8

往期文章

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐