Rongen Zhang
An if statement consists of a logic condition (TRUE or FALSE) followed by one or more statements.
# Template in words
if(a logic condition) {
Get inside the curly brackets and
run this block when the condition is true
} ## [1] "x equals 1"
An if statement can be followed by an optional else statement, which executes when the previous logic expression is false.
name="Tim Cook" ; role = "CEO"
if(role == "CEO") {
print(paste(name, "is a CEO.", sep=" "))
} else {
print(paste(name, "is not a CEO.", sep=" "))
}## [1] "Tim Cook is a CEO."
name = "Jeff Williams" ; role = "COO"
if(role == "CEO") {
print(paste(name, "is a CEO.", sep=" "))
} else {
print(paste(name, "is not a CEO.", sep=" "))
}## [1] "Jeff Williams is not a CEO."
The logic expression in the previous example is role == "CEO".
Alternatively, you can just use a logic variable (TRUE or FALSE):
name="Tim Cook"
is_ceo = TRUE
if(is_ceo) {
print(paste(name, "is a CEO.", sep=" "))
} else {
print(paste(name, "is not a CEO.", sep=" "))
}## [1] "Tim Cook is a CEO."
You can have more than two decision points:
age = 15
if(age < 13) {
print("Kid")
} else if (age < 20) {
# Go into this block if the pervious logic expression is FALSE
# and the current logic expression is TRUE
print("Teenager")
} else {
# Go into this block if all pervious logic expressions are FALSE
print("Adult")
}## [1] "Teenager"
Create a variable grade = "A" and use if-else statements to print its respective value in a 4.0 scale based on the following conversion table. Try different letter grades to see if your if-else statements are correct.
| Letter | Point |
|---|---|
| A | 4 |
| B | 3 |
| C | 2 |
| D | 1 |
| All other letters | 0 |
You often encounter situations when you need to perform the same statements multiple times, potentially over a set of data objects.
Motivating example:
A for loop iterates through every element in a vector.
## [1] "The year was 2001"
## [1] "The year was 2002"
## [1] "The year was 2003"
## [1] "The year was 2004"
In words, for each year that is in the sequence 2001:2004, you execute the code chunk print( paste("The year was", year) )
## [1] 1
## [1] 3
## [1] 5
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"
If you want to skip some items in a for-loop, use the keyword next.
## [1] 1
## [1] 3
## [1] 4
## [1] 5
Continue with our previous exercise on converting letter grades to grade points.
Put letter grades (A, A, C, B, B) in a vector and use for-loop to print out their respective points.
The while loop continually executes a block of statements while a particular condition is true.
## [1] 1
## [1] 2
## [1] 3
for() is better when you want to iterate over a set of elements that you know in advance
while() is better if you find it easy to specify when to run and when to stop.
Note: Every for() could be replaced with a while()
Use a for loop to get the sum of all numbers from 1 to 100
Use a while loop to get the sum of all numbers from 1 to 100
total outside the for/while loop, and change the value of total as you looping through all numbers from 1 to 100sum() function: sum(1:100)A function is a procedure or routine which takes optional inputs and produces an optional output.
So far we have already seen many built-in functions:
seq(), rep(), mean(), length(), …colnames(), rownames()paste()Data structures tie related values into one object
Functions tie related commands into one object
In both cases: easier to understand, easier to work with, easier to build into larger things
In R, you can create your own functions using the following syntax:
my_function <- function(input1, input2, ...) {
# Use the input to do something
return(output) # return a result
}Here is a working example:
hello_world <- function() { # this particular function requires no inputs
print("Hello world!")
# This function has no return statement; return nothing.
}
hello_world() # call the function; don't forget the parentheses## [1] "Hello world!"
Another example:
add_one <- function(num) {
num = num+1 # be sure to match the input variable name
return(num) # return() says what the output is
}
a = add_one(10)
print(a)## [1] 11
greeting <- function(your_name, course_name) {
print(paste0("Hello, ", your_name, ". This is ", course_name))
}
greeting(your_name="Smith", course_name="CIS 4730") ## [1] "Hello, Smith. This is CIS 4730"
## [1] "Hello, Alice. This is CIS 4950"
Write a function that takes two numerical values and return the multiplication of these two values.
Create a vector stop_words to store the following stop words: a, an, and, the, that. Then write a function detect_stop_word that take a word as input and detect if the word is a stop word.
%in% operator from lab-02## [1] FALSE
## [1] TRUE