-
Notifications
You must be signed in to change notification settings - Fork 0
Conditionals and logical operators
We discussed logical operators previously. As a reminder, these allow you to create statements that result in TRUE or FALSE.
Common Logical Operators
< | less than | <= | less than or equal to |
> | greater than | >= | greater than or equal to |
== | equals | != | does not equal |
| | or | & | and |
The function if()
evaluates a condition - whatever is inside the parentheses. If it is TRUE
, it then continues to perform the actions following it in curly brackets.
print("Start run of code.")
if(TRUE){
print("This statement is true.")
}
if(FALSE){
print("This statement is false.")
}
print("End run of code.")
The else
statement. If the conditional is FALSE
, then it performs the code following the curly bracket. We can rewrite the above code block to:
print("Start run of code.")
if(TRUE){
print("This statement is true.")
} else { # here we give the false condition some actions
print("This statement is false.")
}
print("End run of code.")
A combination else if()
lets you list multiple
We want to find out if any number in a vector (the first column of the R dataset iris
) is greater than 7. Here's my first attempt:
if(iris[, 1] > 7){
print("Found sepal length greater than 7.")
}else{
print("Did NOT find sepal length greater than 7.")
}
Turn to a neighbor and discuss:
- What happened? Did it work?
- What are some ways this can be improved on? (Try out some other approaches.)
Next, find out which
elements in the first column of the iris
dataset are greater than 7.
Whenever you are trying to evaluate something, always go back and check that it's working. You can do this by:
- using dummy data, especially to test the extremes
- using subsets of your real data, so you can go back and verify the output
Day 1 or 2
- Basics of R
- Variables and objects
- Functions and packages
- Conditionals and logical operators
- Practice
- Recap
Day 3
Day 4
Day 5
Extra