- Relational Operators in R
- Logical Operators in R
- Conditional Statements in R
- For Loop in R Programming
- While and Repeat Loop in R Programming
- Functions in R Programming
- Creating Functions in R
- Apply Functions in R
- Importing Data from External Data Sources in R
- Importing Data Using read.csv in R
- Import Data using read.table in R
- Importing Data Using data.table – fread in R
- Importing Data from Excel in R
- Using XLConnect in R Programming
- Importing Data from a Database in R
- SQL Queries from R
- Importing Data from Web in R
Logical Operators in R
In programming, you will often come across situations where you will need to evaluate multiple conditions. For example, you may want to perform an action when the price of a stock is above 10 but below 12. Logical operators come into play in such situations. These logical operators allow a program to make a decision based on multiple conditions.
In R, there are five logical operators.
This is called the Logical AND Operator. The logical AND operator (&) returns the boolean value true if both operands are true and returns false otherwise. The following examples illustrate this:
#Assign values to Stock A and Stock B stock_A = 10 stock_B = 12 #Test if Stock A is equal to 10 and Stock B is equal to 12. (stock_A==10) & (stock_B==12)
This will return TRUE if both the conditions evaluate to TRUE. The result will be TRUE as shown below:
> (stock_A==10) & (stock_B==12)  TRUE
Below is another example of & operator on two vectors.
# The following are two vectors containing returns from two stocks over the past five days. stock_A <- c(10, 8, 9, 11, 12) stock_B <- c(8,11,10,10,12) # Stock A exceeds 10 (Inclusive) and Stock B is below 10 (Inclusive) (stock_A >=10) & (stock_B <=10)
This content is for paid members only.
Join our membership for lifelong unlimited access to all our data science learning content and resources.