-
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 statement is inside the parentheses. If it is TRUE
, it then continues to perform the actions following it in curly brackets.
Essentially it asks the following:
print("Start run of code.")
if(TRUE){
print("Our 'if' statement is true.")
}
if(FALSE){
print("Our 'if' statement is false.")
}
print("End run of code.")
Write a few lines of code, where if x
is a number (any number), return that number plus 3.
x <- 7
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("Our 'if' statement is true.")
} else { # here we give the false condition some actions
print("Our 'if' statement is false.")
}
print("End run of code.")
A combination else if()
lets you list multiple conditions.
The exclamation point ahead of a statement is a useful thing to know. It turns TRUE
to FALSE
and vice versa.
1:10
1:10 > 7
!(1:10 > 7) # what are the parentheses for?
# the statement "1 < 7" returns a TRUE
if(1 < 7){
print("One is less than seven.")
}
# we flip that TRUE
if(!(1 < 7)){
print("The conditional is FALSE, so this statement should not print.")
}
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