官术网_书友最值得收藏!

If/else

The if loop will only run a block of code if a certain condition is TRUE. It can be paired with else statements to create an if/else loop. This will work similarly to an if/else loop in other programming languages, though the syntax may be different.

The usual syntax for using if is as follows:

if(test_condition){
some_action
}

Here, the action only occurs if the test_condition evaluates to TRUE, so, for example, if you wrote 4 < 5, the code in the curly braces would definitely run.

If there's something you want to happen, even if the test condition isn't true, you would use an if/else, where the syntax usually looks like this:

if(test_expression){
some_action
}else{
some_other_action
}

Even if the test_expression isn't true, some_other_action will still happen. Finally, you can evaluate multiple test conditions with if/else if/else, as shown in the following syntax:

if(test_expression){
some_action
}else if(another_test_expression){
some_other_action
}else{
yet_another_action
}

Let's do some actual examples to help illustrate these points. Take a look at the following code:

var <- "Hello"
if(class(var) == "character"){
print("Your variable is a character string.")
}

What output would you expect here? What output would you expect if the variable was assigned the value var <- 5 instead? When var is "Hello", the if statement is TRUE, and "Your variable is a character string" will print to the console. However, when var is 5, nothing happens, because we didn't specify an else statement.

With the following code, when var is 5, something will print:

var <- 5
if(class(var) == "character"){
print("Your variable is a character string.")
}else{
print("Your variable is not a character")
}

Because we specified else, we will see the output "Your variable is not a character." This isn't very informative, however, so let's expand and use an else if:

if(class(var) == "character"){
print("Your variable is a character string.")
}else if (class(var) == "numeric"){
print("Your variable is numeric")
}else{
print("Your variable is something besides character or numeric.")
}

If var is 5, now we'll see "Your variable is numeric". What if var was a date? What would print then? Yup, you got it! "Your variable is something besides character or numeric" will print to the console.

主站蜘蛛池模板: 开远市| 新营市| 通州区| 二连浩特市| 万山特区| 金乡县| 婺源县| 峨山| 漠河县| 桃园市| 崇信县| 视频| 和政县| 通渭县| 华宁县| 平湖市| 铜山县| 苗栗市| 古交市| 邵东县| 丰宁| 松江区| 吴堡县| 郁南县| 晋州市| 宽城| 含山县| 合江县| 株洲县| 准格尔旗| 达孜县| 仪征市| 修文县| 淄博市| 文水县| 建瓯市| 邹城市| 筠连县| 科尔| 陇南市| 东莞市|