Within an R object, you can access an element by indexing it.
Indexing tells R which values to output.
Vectors
A vector can be indexed by adding [] after the object’s name and specifying the number of each element.
Matrices
A matrix can be indexed by adding [] after the object’s name and specifying the number of each element. Separate the values by commas for specific indexes.
Data Frames
Data frames can be indexed using the $ operator and [].
Lists
Lists can be indexed using the [[]] for a specific element of a list.
Comparing Numbers
Indexing
Comparing Numbers
if/else Statements
try()
for Loops
Comparing Numbers
You can compare two numbers, or objects, that will result in a logical output.
Comparing Numbers Operators
Operator
Description
>
Greater Than
<
Less Than
>=
Greater than or equal
<=
Less than or equal
==
Equals
!=
Not Equals
Comparing Vectors
When you compare a number to a vector, it will result as a logical vector.
Example
Try the following code and explain what is happening:
if/else Statements
Indexing
Comparing Numbers
if/else Statements
try()
for Loops
if/else Statements
if/else statements are used to conduct specific tasks depending on the conditions
if Statement
An if statement is used to if you want R to perform a specific function if a certain condition is met. An if statement will only run a task if a logical is returned. You will need type if, followed by the condition (as a logical) in parentheses, then the task.
Example
else statement
An else statement will conduct a different task if the if statement does not conduct the tasks.
Example
Chain if/else statement
If you have more than two options, you can chain if/else statements by adding an if statement immediately after the word else.
Example
try()
Indexing
Comparing Numbers
if/else Statements
try()
for Loops
try()
The try() is an extremely powerful function that will prevent a code from stopping if an error occurs.
Example
for Loops
Indexing
Comparing Numbers
if/else Statements
try()
for Loops
for Loops
for loops are used to conduct an iterative task with slight changes to the input. The general format goes as follows:
for (index in vector){ Conduct task}
You will repeat the for loop untie all the elements in the vector have been used.