r语言中对向量求条件语句

To advance with programming, we need to be able to control the flow of the program execution. This controlling happens based upon certain logical conditions. When a condition is met, we expect the program to behave in a certain way, and when a condition is not met, we steer the program in a different way. This is established by means of if else statements in R like several other programming languages.

为了进行编程,我们需要能够控制程序执行的流程。 该控制基于某些逻辑条件进行。 当满足条件时,我们希望程序以某种方式运行,而当不满足条件时,我们将以另一种方式操纵程序。 与if else几种编程语言一样,这是通过R中的if else语句建立的。

R中的If语句 (If Statement in R)

R supports several variants of conditional statements like stand-alone if, if with else, nested if and switch. We will explore one by one in this tutorial. The basic structure of an if block is as follows.

R支持条件语句的多种变体,例如独立if(如果带有else),嵌套if和switch。 在本教程中,我们将一一探讨。 if块的基本结构如下。


if (condition) {
#Code to execute if condition is met
} #This code only works if the condition is true.

Let us illustrate this with a simple example.

让我们用一个简单的例子来说明这一点。


if (a<=5) {
print(a^2)
}

The above code simply checks if a value is less than or equal to 5, and if the condition holds good, it prints the squared value of the number. Let us execute this with a value of 3.

上面的代码只是检查一个值是否小于或等于5,并且如果条件保持良好,它将打印数字的平方值。 让我们以3的值执行它。


[1] 9

如果R中的其他语句 (If Else Statements in R)

When you run this code with a value 6 or 7, you will observe that nothing will be printed at all. This is because we haven’t handled the case where the condition could be false. This is exactly why else blocks are used.

当您以6或7的值运行此代码时,您会发现根本不会打印任何内容。 这是因为我们没有处理条件可能为假的情况。 这就是为什么要使用else块的原因。

Let us try the above if code snippet with an else block now. Do not forget adding a space between else keyword and the opening brace {.

让我们现在尝试上面带有if块的代码段。 不要忘记在else关键字和左括号{之间添加空格。


if(a<=5){
print(a^2)
}
else {
print(a*2)
}

For a value 5, the above program runs the code within the if-block and gives an output 25. However, when a value greater than 5 is given to a, say for example 9, a is multiplied by 2 as specified in the else block.

对于值5,上面的程序在if块中运行代码并给出输出25。但是,当给a大于5的值(例如9)时,将a乘以else中指定的2块。

R中的Ifelse语句 (Ifelse Statement in R)

R also has a special construct named ifelse. When you wish to evaluate a condition against every element of the vector, ifelse construct gives a lot of flexibility. We will explore R vectors in detail later, but for now, we will simply define a small vector of 6 numbers as follows.

R还有一个名为ifelse的特殊构造。 当您希望针对向量的每个元素评估条件时, ifelse构造具有很大的灵活性。 稍后我们将详细探讨R向量,但现在,我们将简单定义一个6个数字的小向量,如下所示。


myvector=c(4,1,6,7,0,4)

Now we wish to divide 100 by each element of the vector and display a result. However, we know that division by 0 gives an error, so we want to handle it in our code. If we write a simple conditional statement using if, the problem is that we don’t know which position in the vector has a zero. The ifelse construct proves very useful in this case.

现在,我们希望将100除以向量的每个元素并显示结果。 但是,我们知道被0除会产生错误,因此我们想在代码中进行处理。 如果我们使用if编写简单的条件语句,则问题在于我们不知道向量中的哪个位置为零。 在这种情况下, ifelse构造非常有用。

The division can be achieved as follows.

该划分可以如下实现。


division <- ifelse(test=myvector==0,yes=NA,no=100/myvector)

This piece of code tests a condition of whether the particular element of myvector is a 0. If it is, the result is populated with an NA value. Else the division is carried out. Let us now check the division result.

这段代码测试了myvector的特定元素是否为0的条件。如果是,则结果将填充NA值。 否则进行划分。 现在让我们检查除法结果。


> division
[1]  25.00000 100.00000  16.66667  14.28571        NA  25.00000

R中嵌套的If Else语句 (Nested If Else Statements in R)

R also supports nesting of if statements within another block. When we wish to check multiple conditions hierarchically dependent on each other, this construct helps.

R还支持在另一个块中嵌套if语句。 当我们希望检查彼此分层依赖的多个条件时,此构造会有所帮助。

We want to check is a number is less than 10 first, then check if it is an even number. Look at the following code that aims to do this.

我们要先检查是否小于10的数字,然后检查是否为偶数。 查看以下旨在实现此目的的代码。


if(a<10){
print("A is less than 10")if(a%%2==0){print("A is even")}else {print("A is odd")}
}

When a is supplied with a value 4, the following result is produced.

当为a提供值4时,将产生以下结果。


[1] "A is less than 10"
[1] "A is even"

堆叠如果其他块 (Stacked If Else Blocks)

We can also stack if-else blocks in the following manner to handle complex logical scenarios.

我们还可以按以下方式堆叠if-else块,以处理复杂的逻辑场景。


if(a<5){
print("Grade is C")
}else if(a>=5&a<10){
print("Grade is B")
}else if(a>=10&a<20){
print("Grade is A")
}else {
print("Invalid marks")
}

R中的Switch语句 (Switch Statement in R)

Finally, we have a special case of conditional statement called switch. If we need to produce an output that is specific to a single variable, switch will prove useful. Without switch we need to write a complicated stack of if blocks.

最后,我们有一个特殊的条件语句,称为switch 。 如果我们需要产生特定于单个变量的输出,则将证明switch是有用的。 没有switch我们需要编写一个复杂的if块堆栈。

Consider an example where we need to fill out a code based upon the “favoritesport” column in the dataset. Cricket gets CR, Football gets FB, Hockey gets HK, Badminton gets BD and Tennis gets TN. This can be easily handled by a switch statement below.

考虑一个示例,在该示例中,我们需要根据数据集中的“ favoritesport”列填写代码。 板球获得CR,足球获得FB,曲棍球获得HK,羽毛球获得BD,网球获得TN。 这可以通过下面的switch语句轻松地处理。


code = switch(EXPR=fx,Cricket='CR',Football='FB',Hockey='HK',Badminton='BD',Tennis='TN')

Let us set fs to “Cricket” and see what out code displays for us.

让我们将fs设置为“ Cricket”,看看将为我们显示什么代码。


fs <- 'Cricket'
code = switch(EXPR=fx,Cricket='CR',Football='FB',Hockey='HK',Badminton='BD',Tennis='TN',NA)
code

[1] "CR"

Look how the switch statement converts the given value to the corresponding code easily. The EXPR here stands for the variable that we wish to switch. Also, NA given as the final option in the switch block is for handling invalid inputs.

看一下switch语句如何轻松地将给定值转换为相应的代码。 这里的EXPR代表我们希望切换的变量。 另外,在切换块中作为最终选项给出的NA用于处理无效输入。

翻译自: https://www.journaldev.com/34719/if-else-statements-in-r

r语言中对向量求条件语句

r语言中对向量求条件语句_R中的条件语句相关推荐

  1. r语言中删除向量的某些元素_R中的向量

    r语言中删除向量的某些元素 Vectors in R are the fundamental data types. This is because the R compiler treats all ...

  2. R语言ggplot2可视化:通过在element_text函数中设置ifelse判断条件自定义标签文本的显示格式:例如、粗体、斜体等

    R语言ggplot2可视化:通过在element_text函数中设置ifelse判断条件自定义标签文本的显示格式:例如.粗体.斜体等 目录

  3. R语言使用Repeat函数多次执行代码块内的语句,实现循环执行任务的功能:repeat没有提供任何检查条件,所以编码者必须给出退出重复循环的条件(一般使用if和break)

    R语言使用Repeat函数多次执行代码块内的语句,实现循环执行任务的功能:repeat没有提供任何检查条件,所以编码者必须给出退出重复循环的条件(一般使用if和break) 目录

  4. R语言如何向向量中追加一个元素?

    R语言如何向向量中追加一个元素? 目录 R语言如何向向量中追加一个元素? R语言是解决什么问题的? R语言如何向向量中追加一个元素? R语言是解决什么问题的? R 是一个有着统计分析功能及强大作图功能 ...

  5. R语言使用单个向量创建矩阵数据、通过byrow参数指定从向量转化为矩阵的过程中的数据排布方式

    R语言使用单个向量创建矩阵数据.通过byrow参数指定从向量转化为矩阵的过程中的数据排布方式 目录 R语言使用单个向量创建矩阵数据.通过byrow参数指定从向量转化为矩阵的过程中的数据排布方式 R语言 ...

  6. R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数、均值和中位数、使用funs函数指定函数列表

    R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数.均值和中位数.使用funs函数指定函数列表 目录

  7. R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数、均值和中位数、使用list函数指定函数列表并指定自定义函数名称

    R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数.均值和中位数.使用list函数指定函数列表并指定自定义函数名称 目录

  8. R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的方差

    R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的方差 目录 R语言dplyr包summarise_at函数

  9. R语言dplyr包summarise_if函数计算dataframe数据中所有数值数据列的均值和中位数、基于条件进行数据汇总分析(Summarize all Numeric Variables)

    R语言dplyr包summarise_if函数计算dataframe数据中所有数值数据列的均值和中位数.基于条件进行数据汇总分析(Summarize all Numeric Variables) 目录

最新文章

  1. ensp删除静态路由命令_eNSP配置静态路由
  2. ide硬盘接口图 sata硬盘接口图 SCSI硬盘接口图
  3. mysql处理存在则更新,不存在则插入(多列唯一索引)
  4. 操作系统核心原理-5.内存管理(中):分页内存管理
  5. mysql合并表中的数据
  6. c语言编译生成cpp,C语言的编译过程
  7. nfc加密卡pm3和pm5区别_小米手环4/5 NFC添加加密门禁
  8. 各种控制列表--前缀列表
  9. 并注册烧写钩子 获取启动介质类型_鸿蒙OS开源代码精要解读之—— 系统服务框架子系统(服务启动)...
  10. mysql扩展文件_MySQL中的空间扩展
  11. liunx下文件授权可执行权限chmod
  12. java俄罗斯方块代码_java俄罗斯方块代码.doc
  13. 7-15 福到了 c语言,7-54 福到了 (15 分)
  14. visio 中取消 交叉连接线的拱形的方法
  15. SQL中modify和alter用法区别
  16. MongoDB 安全安全检查列表
  17. php rewrite 开启,Apache Rewrite 开启和使用方法
  18. 85D - Sum of Medians
  19. instruction-tuning
  20. apt-get install E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing

热门文章

  1. Laravel 5.x 启动过程分析 [转]
  2. JavaScript - 初识
  3. 30个你 “ 不可能全部会做 ” 的javascript题目
  4. POJ 3415 (后缀数组)
  5. MATLAB IIR滤波器设计函数buttord与butter
  6. 09-Python入门学习-函数基础与参数
  7. linux实现多台服务器文件同步
  8. fail-fast机制
  9. iOS 开发 - 绘制辉光效果
  10. Android中GridView实现互相添加和删除