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

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语言中对向量求条件语句

    原文作者:cunchi4221
    原文地址: https://blog.csdn.net/cunchi4221/article/details/107477856
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞