R Programming Concepts: Final Exam Reviewer
This reviewer summarizes the core topics and syntax presented in the sources.
1. Loops in R
Loops are used for automating a multi-step process by repeating sequences of actions. The
sources cover three types: While, Repeat, and For loops.
• While Loop
o Description: A while loop checks a logical condition and continues running as
long as the condition is true.
o Syntax:
o while (condition) {
o expression
o }
o Key Points:
▪ If the condition is always true, the loop becomes an infinite loop.
▪ You need to include code within the loop's body that will eventually make
the condition false to stop the loop.
▪ To see the current loop value, you need to wrap the variable inside the
print() function.
▪ An if-else statement can be used within a while loop.
o Sample Application: Summing digits of a number to check for an Armstrong
number, calculating factorial, simple counter loops.
• Repeat Loop
o Description: The Repeat loop executes the same code repeatedly until a stop
condition is met.
o Syntax:
o repeat {
o commands
o if(condition) {
o break
o }
o }
o Key Points:
▪ A Repeat loop does not have an inherent condition to terminate.
▪ A programmer must specifically place a condition within the loop's body
and use the break statement to terminate it.
o Sample Code: Simple loops printing a vector or counter, terminating with a
break condition.
• For Loop
o Description: Executes a set of statements once for each item in a vector, array,
list, etc.. Works like an iterator method.
o Syntax:
o for (x in sequence) {
o print(x)
o }
(General form based on samples)
o Key Points:
▪ Can iterate over a sequence of numbers (1:10), vectors (dice), etc.
▪ Nesting: For loops can be nested within each other to iterate over multi-
dimensional structures like matrices or arrays.
▪ The rep() function can be used to replicate values or structures, often
useful when working with loops.
o Control Statements within For Loops:
▪ break: Stops the loop before iterating through all items.
▪ next: Skips the current iteration without terminating the loop.
▪ If .. Else statements can be combined with a For Loop.
o Sample Code: Iterating through sequences, vectors, calculating squares, matrix
operations, simulations using sample() and rnorm().
2. Functions in R
A function is a set of statements organized together to perform a specific task. R has built-in
functions and allows users to create their own.
• Types of Functions:
o In-built functions: Directly called in the program without defining them first
(e.g., seq(), mean(), max(), sum(), paste()).
o User-defined functions: Created by the user for specific tasks. Once created,
they can be used like built-in functions.
• Function Components:
o Function Name: The name used to call the function; stored as an object in the R
environment.
o Arguments: Placeholders for values passed to the function when it's invoked.
Arguments are optional and can have default values.
o Function Body: Contains the statements that define what the function does.
o Return Value: The last expression in the function body that is evaluated becomes
the return value.
• Creating User-defined Functions:
• new.function <- function(arguments) {
• # Function body (statements)
• # ...
• return_value # Optional, last evaluated expression is returned by
default
• }
(General form based on samples)
• Calling a Function:
o By position: Supply argument values in the same sequence as defined.
o By name: Supply argument values by explicitly naming the arguments, allowing
a different sequence.
o With default arguments: Call without providing values for arguments that have
defaults. You can also provide new values to override defaults.
o Examples: Functions for printing squares, performing calculations with multiple
arguments, reading integer input, countdown, temperature conversions (Celsius to
Kelvin, Fahrenheit to Celsius, Fahrenheit to Kelvin).
3. Flow Control Statements in R
These statements allow you to make decisions and take actions based on conditions.
• If Statement
o Description: Executes a block of code if a condition is true.
o Syntax:
o if (condition) {
o # Code to execute if condition is TRUE
o }
o Key Points:
▪ Can test a single element, not a vector of elements. When applied to a
vector, it only checks the first observation.
• If-Else Statement
o Description: Executes one block of code if the condition is true, and another
block if the condition is false.
o Syntax:
o if (condition) {
o # Code if condition is TRUE
o } else {
o # Code if condition is FALSE
o }
• Nested If-Else Statements
o Description: Placing an if-else statement inside the action block of another if-
else statement. These nested statements are independent.
o Example Structure:
o if (condition1) {
o # Action 1
o } else {
o if (condition2) {
o # Action 2
o } else {
o # Action 3
o }
o }
• Multiple If-Else Statements (if-else if-else)
o Description: Allows checking multiple conditions in a single statement.
o Structure: if (<condition 1>) { <action 1> } else if (<condition
2>) { <action 2> } else { <action 3> }.
o Key Points:
▪ If <condition 1> is true, <action 1> is executed.
▪ Otherwise, <condition 2> is evaluated. If true, <action 2> is executed.
▪Otherwise (if both <condition 1> and <condition 2> are false),
<action 3> is executed.
▪ Requires one if, can have one or more else if, and can have zero or one
else block.
o Example Structure:
o if (condition1) {
o # Action 1
o } else if (condition2) {
o # Action 2
o } else if (condition3) {
o # Action 3
o } else {
o # Default action
o }
• Switch Statement
o Description: A multiway branch statement that tests an expression against a list
of values. It acts as a substitute for long if statements that compare a variable to
several values.
o Syntax:
o switch(expression, case1, case2, case3....)
o # or
o switch(expression, list)
o How it works: The expression is evaluated.
▪ Numeric Expression: If the expression evaluates to a number, switch()
returns the item in the list corresponding to that numerical position
(index). If the number is out of range, NULL is returned.
▪ String Expression: If the expression evaluates to a string, switch()
searches the list for an element with a matching name and returns its
value.
o Key Points:
▪ Follows an approach of mapping and searching.
▪ If there is more than one match for a specific value (especially with
string expressions), the switch statement will return the first match
found.
▪ Default Case: An unnamed element in the list serves as a default case if
no match is found. If there is more than one unnamed element and no
match, an error occurs.
o Sample Code: Returning values based on numeric or string input, performing
operations based on user options (mean, mode, median).
4. Graphs in R
R provides libraries for creating various charts and graphs. The sources specifically cover Pie
Charts, Bar Charts, and Line Charts.
• Pie Chart
o Description: Represents values as slices of a circle with different colors and
labels.
o Function: pie().
o Syntax: pie(x, labels, radius, main, col, clockwise).
o Key Parameters:
▪ x: Vector of numeric values for the slices.
▪ labels: Descriptions for the slices.
▪ radius: Radius of the circle (-1 to +1).
▪ main: Title of the chart.
▪ col: Color palette.
▪ clockwise: Logical value for drawing direction.
o Additional Features: Can add slice percentages and chart legends. Requires the
plotrix library for 3D pie charts using pie3D().
o Saving Charts: Charts can be saved to files (e.g., .png, .jpg) using png() or
jpeg() before plotting and dev.off() after.
• Bar Chart
o Description: Represents data in rectangular bars proportional to the variable's
value. Can be vertical or horizontal.
o Function: barplot().
o Syntax: barplot(H, xlab, ylab, main, names.arg, col).
o Key Parameters:
▪ H: Vector or matrix of numeric values for the bars.
▪ xlab: Label for the x-axis.
▪ ylab: Label for the y-axis.
▪ main: Title of the chart.
▪ names.arg: Vector of names under each bar.
▪ col: Colors for the bars.
o Types: Basic bar chart, Stacked Bar Chart (using a matrix for H and adding a
legend).
o Saving Charts: Saved similarly to pie charts using png() and dev.off().
• Line Chart
o Description: Connects points with line segments, typically used to identify
trends.
o Function: plot().
o Syntax: plot(v, type, col, xlab, ylab).
o Key Parameters:
▪ v: Vector of numeric values.
▪ type: Specifies what to draw ("p" for points, "l" for lines, "o" for both).
▪ xlab: Label for the x-axis.
▪ ylab: Label for the y-axis.
▪ main: Title of the chart.
▪ col: Colors for points and lines.
o Multiple Lines: Additional lines can be added to an existing plot using the
lines() function.
o XY Scatter Plot: The plot() function can also be used for scatter plots, e.g.,
plot(x, y, ...). abline() can add a regression line.
o Saving Charts: Saved using png() and dev.off().