1.4 Control Structures
From the rules of programming, codes are generally executed from top to bottom.
This makes our functions limited, because we have not introduced a way to make comparisons and select different command based on the result of the comparison.
Furthermore, some processes require repitition. If each line of code we wrote were only executed once, programming would be a very unproductive exercise.
Control Statements will give us these abilities.
1.4.1 Selection Control
These are the IF
statements.
R follows the mainstream syntax for declaring conditional statements. If one wants to perform conditional checks, then you may use this following codes:
Single Selection
if(condition) action if(condition) {action1; action2; action3}
Double Selection
if(condition){ action1; action2; action3 }else{ alt action1; alt action2; alt action3 }
Multiple Selection
if(condition) { action1; action2; action3 }else if(condition) { alt action1; alt action2; alt action3 }else if(condition){ more actions }else { more actions }
In above syntax, the condition
must be a logical value (takes value of TRUE
or FALSE
only)
Example:
x <- -5
if(x > 0){
print("x is positive")
}else if (x < 0){
print("x is negative")
}else{
print("x is zero")
}
1.4.2 Repetition Control
In R, there are 3 loop control structures.
for
loopCommonly used if the number of iterations is fixed. The actions will be executed based on the elements of the defined vector.
## [1] 1 ## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5
while
loopIt repeats the instructions given when the condition indicated is still satisfied.
## [1] 10
repeat
loopSimply repeat all actions given. This loop never terminates, unless the system encounters an explicit command to stop the loop.
## [1] 1 ## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5
Additionally, break
and next
commands transfer control within a loop.
Practice Exercises
In these exercises, it is better if you create different R script for each item.
1. Day of the week
The readline()
function in R reads a line from the terminal (in interactive use).
For example, if you run the following code:
x <- readline("Enter Number: ")
The following will appear in the console:
Enter Number:
Which allows a user to enter a value that will be the value of the object x
.
For the following, use readline()
to allow input from the user, and use print()
to print the required output. You can also use the message()
to show either an error message or a diagnostic message.
When you input an integer value but R reads it as a character, but you want to convert it to an
integer, use the function as.integer()
.
x <- as.integer(readline("Enter a Number:"))
Tasks:
Write an R program that takes an integer input from the user between 1-7 (inclusive) and displays the corresponding name of the week.
The program should be able to filter values not in the range or values which are not exact (e.g. 3.8 or any non-numeric character). For such case, it should output an error message saying “Input Value should be from 1 to 7”) and allows the user to reenter another value without having to run the program again.
This should utilize if-else/nested if statements.
You may use any loop structure to repeat a process and break to end the loop if some condition is satisfied/not satisfied.
After you write your program in an R Script, click “Source” instead of “Run”.
Examples:
Input: 7 Output: “Saturday”
Enter Number: 7 [1] "Saturday"
Input: 9 which is not a number from 1 to 7.
Output: None yet. Show message, then allow input again.
Enter Number: 9 Input value should be from 1 to 7. Enter Number:
Input: a non-numeric character “not a number”
Output: None yet. Show message, then allow input again.
Enter Number: not a number Input value should be from 1 to 7. Enter Number:
2. ATM withrdawal
Suppose an ATM can only dispense 1000-peso-bills, 500-peso-bills, and 100-peso bills. Create a function that will:
Only accept positive values divisible by 100 (i.e., amount to be withdrawn). Here, you will review the concept of “input validation” such that before your function performs the task, it would first check the value of the input. If the value does not satisfy what was required, the function may return a message.
Tell the number of bills per denomination (can be a vector that contains the following: [number of 1000-peso bills, number of 500-peso bills, number of 100-peso bills])
Bind this function to the name atm_denom
, and test this function in another code chunk (You may use your own test values).
Note that for this item, the priority bill would be 1000 pesos, followed by 500 pesos, and followed by 100 pesos, i.e., the function would only start counting the 500-peso bills if it is already not possible to add 1000-peso bills in the total number of bills, and the function would only start counting the 100-peso bills if it is already not possible to add 500-peso bills in the total number of bills.
Assume that the ATM machine has unlimited 1000-peso-bills, 500-peso-bills, and 100-peso bills.
You may use R infixed operators (arithmetic, comparison, and logical operators).
Do not forget to include documentations. Do NOT use any other built-in function in R, and do NOT install and load packages.
Example:
## [1] "Dispense 10 1000-peso bills."
## [1] "Dispense 1 500-peso bills."
## [1] "Dispense 0 100-peso bills."
## [1] "Dispense 2 1000-peso bills."
## [1] "Dispense 1 500-peso bills."
## [1] "Dispense 4 100-peso bills."
## [1] "Withdrawal amount must be divisible by 100."