R Programming Fundamentals
上QQ阅读APP看书,第一时间看更新

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.