Simply put, Boolean logic refers to binary values that can are akin to a switch:
In R, the inbuilt options for Boolean logic are TRUE/FALSE.
This is how combination of Boolean values evaluate with && (AND), || (OR), and xor.
| ( P ) | ( Q ) | ( P AND Q ) | ( P OR Q ) | ( P ) |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | F |
| F | T | F | T | T |
| F | F | F | F | T |
if, else if, else: These can be used to instruct a particular part of the code to be run or not run.
For example take this instruction:
If x is greater than y, print “Yes o!”, otherwise print “No way!”
When the expression in if() is TRUE, the code in that part is executed. If FALSE, the else part is executed.
What is the result?
Loops allow us to run a code block over and over again.
For a simple explanation of loops, read this article.
Imagine having to write code that has the same statement repeated:
## `repeat`
::: {.cell}
```{.r .cell-code}
# write repeat loop that prints all the even numbers from 2-10
# via incrementing the variable, i <- 0
i <- 0
repeat{
i <- i + 2
print(i)
if(i >= 10)
break
}
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
:::
whilefor# 5. Print the first four numbers of this sequence
x <- c(7, 4, 3, 8, 9, 25)
for (i in 1:4)
print(x[i])[1] 7
[1] 4
[1] 3
[1] 8
# 6. write a for() loop that prints all the letters in
y <- c("q", "w", "e", "r", "z", "c")
for (i in 1:length(y))
print(y[i])[1] "q"
[1] "w"
[1] "e"
[1] "r"
[1] "z"
[1] "c"
Task: Read a table from a CSV file called mockdata.csv.
Use read.csv() function to read the file into R and at the same time create an object called mydata.
no key age sex height location
1 1 A 21 male 0.96 Abuja
2 2 B 22 female 1.86 Abuja
3 3 C 23 female 1.68 Abuja
4 4 D 24 male 1.13 Abuja
5 5 E 25 female 1.40 Lagos
6 6 F 26 female 1.52 Kaduna
7 7 G 27 female 1.06 Makurdi
8 8 H 28 male 1.25 Abuja
9 9 I 29 male 1.06 Lagos
10 10 J 30 male 1.12 Abuja
11 11 K 31 female 0.96 Sokoto
12 12 L 32 female 0.93 Lagos
13 13 M 33 female 1.17 Abuja
14 14 N 34 female 1.31 Makurdi
15 15 O 35 male 1.48 Makurdi
16 16 P 36 male 0.99 Lagos
17 17 Q 37 female 1.31 Makurdi
18 18 R 38 male 1.24 Sokoto
19 19 S 39 female 1.25 Lagos
20 20 T 40 female 0.96 Sokoto
Use a loop to check the types of the columns