Logicals are a set of operations that act on raw, logical, and number-like vectors. They ususaly test if the relationship between two vectors is TRUE or FALSE. They can be used for both simple calculations and comparisons and for more complex tasks such as setting up conditions for loops, looking and prescreening data before running tests, etc.
== - tests equality of the two elements
3 == 3 #This will return TRUE
## [1] TRUE
2 == 3 #This will return FALSE
## [1] FALSE
!= - tests ineequality of the two elements
3 != 4 #This will return TRUE
## [1] TRUE
1 != 1 #This will return FALSE
## [1] FALSE
<, >, <=, >= - compare the values
3 < 2 #This will return FALSE
## [1] FALSE
3 > 2 #This will return TRUE
## [1] TRUE
5 <= 4 #This will return FALSE
## [1] FALSE
5 >= 5 #This will return TRUE
## [1] TRUE
Reverses the Boolian value. So if your value was TRUE, negation will turn it into FALSE. Putting “!” in fron of the expression, as in the example below, will negate the expression.
(3 < 2) #This alone will return FALSE
## [1] FALSE
!(3 < 2) #But after negation this statement is true
## [1] TRUE
Tests if both conditions are true. For simple tests, can use singular & and double &&, both mean AND. & - Returns a vector of logical values for each item in vector z if both conditions are satisfied. && - Tests if all elements in vector satisfy both conditions and returns a single logical value. Thus, for equality testing, either one works fine. For inequality testing, application of & or && depends on your goal.
x <- 1; y <- 2 #Setting up the values
(x == 1) & (y == 2) #This will return TRUE
## [1] TRUE
(x == 1) && (y == 3) #This will return FALSE
## [1] FALSE
Beware using & and && in more complex expressions for the meanings will vary. Test on simple functions first, as in the examples below.
z <- 1:6 #Setting up the vector
z[(z>2) & (z<5)] #Returns elements that satisfy both conditions
## [1] 3 4
(z > 2) & (z < 5) #Returns a vector of logical values for each item in vector z if both conditions are satisfied
## [1] FALSE FALSE TRUE TRUE FALSE FALSE
(z > -2) && (z < 50) #Tests if all elements in vector satisfy both conditions and returns a single logical value
## [1] TRUE
We have a vector a that has values 1 - 100. We want to find out what numbers are divisible by 7 and 13.
a <- 1:100 #Setting up the vector
(a %% 7 == 0) && (a %% 13 == 0) #Tests if all elements in vector satisfy both conditions and returns a single logical value. FALSE is returned because not all numbers in the vector are divisible by 7 and 13.
## [1] FALSE
(a %% 7 == 0) & (a %% 13 == 0) #Returns a vector of logical values for each item in vector a if both conditions are satisfied. We can see that there is one TRUE in the sea of FALSE.
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [23] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [34] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [45] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [56] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [67] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [78] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [89] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [100] FALSE
a[(a %% 7 == 0) & (a %% 13 == 0)] #Returns elements that satisfy both conditions. In this example, it is 91.
## [1] 91
Tests if any of the conditions is true. For simple tests, can use singular | and double ||, both mean OR. | - Returns a vector of logical values for each item in vector z if any condition is satisfied. || - Tests if any element in vector satisfy any conditions and returns a single logical value. Thus, for equality testing, either one works fine. For inequality testing, application of | or || depends on your goal.
x <- 1; y <- 2 #Setting up the values
(x == 1) | (y == 2) #This will return TRUE
## [1] TRUE
(x == 1) || (y == 3) #This will return TRUE
## [1] TRUE
Beware using | and || in more complex expressions for the meanings will vary. Test on simple functions first, as in the examples below.
z <- 1:6 #Setting up the vector
z[(z>2) | (z<5)] #Returns elements that satisfy any condition
## [1] 1 2 3 4 5 6
(z > 2) | (z < 5) #Returns a vector of logical values for each item in vector z if any condition is satisfied
## [1] TRUE TRUE TRUE TRUE TRUE TRUE
(z > 2) || (z < 5) #Tests if any element in vector satisfy any conditions and returns a single logical value
## [1] TRUE
We have a vector a that has values 1 - 100. We want to find out what numbers are divisible by 7 or by 13.
a <- 1:100 #Setting up the vector
(a %% 7 == 0) || (a %% 13 == 0) #Tests if any elements in vector satisfy any of the two conditions and returns a single logical value. FALSE is returned because not all numbers in the vector are divisible by either 7 or 13.
## [1] FALSE
(a %% 7 == 0) | (a %% 13 == 0) #Returns a vector of logical values for each item in vector a if at least one condition is satisfied. We can see that there are a couple of TRUE in the sea of FALSE.
## [1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
## [12] FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
## [23] FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
## [34] FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE
## [45] FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE
## [56] TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE
## [67] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
## [78] TRUE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
## [89] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
## [100] FALSE
a[(a %% 7 == 0) | (a %% 13 == 0)] #Returns elements that satisfy any of the two conditions. In this example, these numbres are 7, 13, 14, 21, 26, 28, 35, 39, 42, 49, 52, 56, 63, 65, 70, 77, 78, 84, 91, 98.
## [1] 7 13 14 21 26 28 35 39 42 49 52 56 63 65 70 77 78 84 91 98
Similarly to Excel function if, ifelse tests an argument, and if that argument is true, ifelse will return the 1st specified value, if argument is false it will return the 2nd specified value. Has three inputs: 1 - expression to test, 2 - what to return if true, 3 - what to return if false
ifelse(1 == 0,1,0) #Returns 0 for 1 is not equal to 0
## [1] 0
Note that ifelse can be nested in itself multiple times, like in Excel
ifelse(1 == 0,1, ifelse(1 == 2,2,0)) #Returns 0
## [1] 0
First, the outer ifelse clause is evalueted. 1 == 0 is FALSE, thus R executes the false portion of the outer ifelse that has another nested ifelse clause. 1 == 2 is alse FALSE, thus 0 is returned because it is specified as a result if the expression is false.
Expanded version of if clause that can be used in more complex ways. If can be used alone or with else.
if(1 < 2) print ('Hello') #Prints 'Hello'
## [1] "Hello"
if(1 > 2) print ('Hello') else print('Bye') #Print 'Bye'
## [1] "Bye"
If the condition inside is false and there is no else, R will do nothing because nothing is specified for this case.
if(1 > 2) print ('Hello') #Runs and does nothing
Loops iterate over a block of code multiple times based on some criteria. There are three loop functions: * Repeat * While * For Tools help shape loops to reach the end goal. There are two tools: * Break * Next
Note: Some loops can be tough on computer RAM, so bevare crushing R or even your computer. Note: Beware of creating an infinite loop, a loop that does not have any exit condition so it will run forever. You will need to press stop button which will lead to you not getting a result.
Repeat - used to iterate over a block of code multiple times. There is no check in repeat loop to exit. Must put a condition explitictly into the loop and use break to exit the loop (break and next will be covered later). If no condition is applied, you will create an infinite loop.
i <- 0 #Setting up the counter i
repeat{
print(i) #Code that tells the program what to do
#Next two lines are set up as condition check to exit the loop
i <- i + 1 #Increasing the counter
if( i == 30) break #setting up the condition when to break the loop
}
## [1] 0
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 15
## [1] 16
## [1] 17
## [1] 18
## [1] 19
## [1] 20
## [1] 21
## [1] 22
## [1] 23
## [1] 24
## [1] 25
## [1] 26
## [1] 27
## [1] 28
## [1] 29
The code results in numbers from 0 to 29 because given the way the code is written, when 29 is reached it is printed, then increased by 1, and then tested in the if clause where i == 30 is true and the loop is stopped. The order in which you write the loop statements matters!
Note that break can be put into curvy parentheses of if statement, but it is not neccessary.
While - used to iterate over a block of code multiple times as long as specified condition is met.
#Setting up the starting value
x=0
#The loop
while (x < 42) { #This specifies that the loop will run as long as the condition is met. Once condition is not met (x>42) the loop will stop
x<-1+x #Increasing the counter
print(x) #Code that tells the program what to do
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 15
## [1] 16
## [1] 17
## [1] 18
## [1] 19
## [1] 20
## [1] 21
## [1] 22
## [1] 23
## [1] 24
## [1] 25
## [1] 26
## [1] 27
## [1] 28
## [1] 29
## [1] 30
## [1] 31
## [1] 32
## [1] 33
## [1] 34
## [1] 35
## [1] 36
## [1] 37
## [1] 38
## [1] 39
## [1] 40
## [1] 41
## [1] 42
The code returns numbers 1 - 42. When 41 is reached, the x is increased by 1 and 42 is displayed. Now x = 42 that makes statement x < 42 false and the loop is stopped. The while loop does not need a break clause to stop because this feature is built in, but it is important to include incremental code so that the loop does not turn into an infinite loop.
For - used to iterate over a vector. The statement of the program is repeated for as many times as there are units in the vector.
z <- c(2, 4, 6, 8)
for (i in z) { # The condition inside tells the loop how many times to run it
print(i^2) # Code that tells the program what to do
}
## [1] 4
## [1] 16
## [1] 36
## [1] 64
The code returns 4 numbers, the squared elements of the vector z, because there are only 4 items in z.
Another common use of the for loop is to run some code for the length of the vector.
z <- c(2, 4, 6, 8) #Setting up the vector
for (i in 1:length(z)) { # The condition inside tells the loop how many times to run it
print(z[i]^2) # Code that tells the program what to do
}
## [1] 4
## [1] 16
## [1] 36
## [1] 64
The for loop changes the value of i from 1 to the lenght of the vector z by 1 and does an operation on i-th element of z, in this example it squares it. Thus the result is same as for the previous code, but has a slightly different approach. This gives us the ability to create a calculation that will not have a challenge having a vector of any length as an input. Other common uses of for loop is using 1:seq (1:seq(1, 100)) and 1:range.
A break statement is used inside a loop to stop the iterations and flow the control outside the loop.
x <- 1:5 #Create a vector
for (val in x) { #Set up the loop so that variable "val" takes each value in x in order
#The val is used in the next two lines in the loop statement
if (val == 3) {break} #Compare the val to 3, exit the loop if val equals 3
print(val) #If val is not 3, print the item associated with val in this round of the loop
}
## [1] 1
## [1] 2
R returns values 1 and 2 only for when 3 is reached, the if statement stops the loop and 3, 4, and 5 do not show up.
In case of nested loops, the breaks exits the loop that is being evaluated.
#Set up two different vactors to demonstrate the effect of the nested loops
x <- 1:5
y <- 10:50
for (val in x) { #Setting up the first loop that will repeat the second loop and print the value of val for every item in x
for (val2 in y) { #Setting up the second loop to repeat two statements
if (val2 == 15) {break} # 1. Test if val2 equal 15, exit the loop if yes
print(val2) # 2. Print the value of val2
}
print(val) #When the nested loop is exited, val from x for which the nested loop was ran is printed
}
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 1
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 2
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 3
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 4
## [1] 10
## [1] 11
## [1] 12
## [1] 13
## [1] 14
## [1] 5
The break is used in the nested loop so the result is all values of x and only the values of y below 15. Note the repeated pattern, the nested loop is repeated for each value of the outside loop.
A next statement is used inside a loop to skip the iterations of a loop without terminating it.
x <- 1:5 #Settign up the vector
for (val in x) { #Setting up the loop
if (val == 4) {next} #Applying the next to skip value of 4
print(val) #Print the value of val
}
## [1] 1
## [1] 2
## [1] 3
## [1] 5
R returns 1 though 5 but skips 4 because if statement is true and applies next.