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

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.

主站蜘蛛池模板: 潜江市| 攀枝花市| 万年县| 荔浦县| 汉中市| 洪泽县| 翁源县| 宁陕县| 时尚| 临城县| 丽江市| 重庆市| 泸州市| 博湖县| 得荣县| 临猗县| 镇巴县| 黄浦区| 舒兰市| 房产| 无棣县| 蒙自县| 和静县| 天长市| 琼中| 武川县| 武平县| 阳东县| 蓬安县| 榆林市| 莱西市| 长海县| 河曲县| 营山县| 长泰县| 离岛区| 南昌市| 昌江| 枝江市| 江源县| 陇西县|