Week 1

Combination of everything done through the week.

#install.packages("ks")

#library(ks)

#To install a package in R I'll have to use the command "install.package()"
#This gives the user a shortcut way to int=stall simply his/her package which
#Which is also known as "libraries of command"!

#The above package "ks" is just an example on how to install a package which I


#Knowing how to perform an assignment with R.
M <- rep(seq(1:3), time=2)

B <- print(!M)
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
print(!B)
## [1] TRUE TRUE TRUE TRUE TRUE TRUE
`my result` <- 91

print(`my result`)
## [1] 91
M <- seq(1:20)

K <- mean(M, trim=0.3, na.rm = FALSE)

print(K)
## [1] 10.5
J <- c("Alex", "John","Hassana", "Jumai", "Hajara")

print(J)
## [1] "Alex"    "John"    "Hassana" "Jumai"   "Hajara"
m <- matrix()


B <- c(2, 5, 13, 19, 11, 20)

print(B>10)
## [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE
#How to call an object
for (i in seq(1:10))

  print(i)
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
for (i in seq(2:28)) {
 print(i)
}
## [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
#Some Little work through matrix and mean with diag and mean functions.

A <- diag(x=3)
print(A)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1
#Example from the book of R, page 43.
d <- c(0:10,50)

dm <- mean(d)
v <- c(dm,mean(d, trim = 0.10))

print(v)
## [1] 8.75 5.50
print(d)
##  [1]  0  1  2  3  4  5  6  7  8  9 10 50
#Mean
F <- c(1,2,NA,5)
 mean(F)   #After running the code it results:[1] NA
## [1] NA
 #But when I return with a more explicit but reversed code for the mean, such as:
 mean(F,na.rm = TRUE)  #I got this result:[1] 2.666667
## [1] 2.666667
 #Where the na.rm means ("not available. remove"), which helps remove the NA
 #by the command "na.rm".


z <- c(0+6i, 1-9i, 2+0i, 8+15i, 1+2i)

Table <- data.frame(
  Complex = z,
  Imaginary = Im(z),
  Real = Re(z),
  Argument = Arg(z),
  Modulus = Mod(z),
  Conjugate = Conj(z)
)

print(Table)
##   Complex Imaginary Real  Argument   Modulus Conjugate
## 1   0+ 6i         6    0  1.570796  6.000000     0- 6i
## 2   1- 9i        -9    1 -1.460139  9.055385     1+ 9i
## 3   2+ 0i         0    2  0.000000  2.000000     2+ 0i
## 4   8+15i        15    8  1.080839 17.000000     8-15i
## 5   1+ 2i         2    1  1.107149  2.236068     1- 2i
#Basic plotting in R
foo<-1:5
bar<-6:10
baz <- cbind(foo,bar)

plot(baz)

#First Exercise: (a). Say the word cat aloud.

Alushi<-"Say the word cat aloud"

print(Alushi)
## [1] "Say the word cat aloud"
#Second Exercise: (b). Find the solution to 1+1

L<-1
O<-1
G<-L+O

print(G)
## [1] 2

Part (1)

Continuation of Chapter 2, Wed (6,8,2025)

# Sequence creation with rbind
Mycob <- c(rbind(seq(1,86), seq(6,91)))
print(Mycob)
##   [1]  1  6  2  7  3  8  4  9  5 10  6 11  7 12  8 13  9 14 10 15 11 16 12 17 13
##  [26] 18 14 19 15 20 16 21 17 22 18 23 19 24 20 25 21 26 22 27 23 28 24 29 25 30
##  [51] 26 31 27 32 28 33 29 34 30 35 31 36 32 37 33 38 34 39 35 40 36 41 37 42 38
##  [76] 43 39 44 40 45 41 46 42 47 43 48 44 49 45 50 46 51 47 52 48 53 49 54 50 55
## [101] 51 56 52 57 53 58 54 59 55 60 56 61 57 62 58 63 59 64 60 65 61 66 62 67 63
## [126] 68 64 69 65 70 66 71 67 72 68 73 69 74 70 75 71 76 72 77 73 78 74 79 75 80
## [151] 76 81 77 82 78 83 79 84 80 85 81 86 82 87 83 88 84 89 85 90 86 91
# Vector creation
Myvec <- c(1,3,1,42)
foo <- 32.1   # define foo before using
myvec2 <- c(3,-3,2,3.45,1e+03,64^0.5,2+(3-1.1)/9.44,foo)

# combinations of vectors
myvec3 <- c(Myvec,myvec2)
print(myvec3)
##  [1]    1.000000    3.000000    1.000000   42.000000    3.000000   -3.000000
##  [7]    2.000000    3.450000 1000.000000    8.000000    2.201271   32.100000
# Creation of sequence
myseq2 <- seq(from=foo,to=(-47+1.5),length.out=5)
print(myseq2)
## [1]  32.1  12.7  -6.7 -26.1 -45.5
# Repetition examples
rep(x=1,times=5)
## [1] 1 1 1 1 1
rep(x=c(1,2,3),times=3)
## [1] 1 2 3 1 2 3 1 2 3
rep(x=c(2,3,5),times=6,each=2)
##  [1] 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5
# Join sequences
goo <- 4
foo+1
## [1] 33.1
# Sorting
sort(x=c(2.5,-1,-10,3.44),decreasing = FALSE)
## [1] -10.00  -1.00   2.50   3.44
sort(x=c(2.5,-1,-10,3.44),decreasing = TRUE)
## [1]   3.44   2.50  -1.00 -10.00
foo <- seq(from=4.3,to=5.5,length.out=8)
foo
## [1] 4.300000 4.471429 4.642857 4.814286 4.985714 5.157143 5.328571 5.500000
bar <- sort(foo,decreasing=TRUE)
bar
## [1] 5.500000 5.328571 5.157143 4.985714 4.814286 4.642857 4.471429 4.300000
sort(c(foo,bar),decreasing=FALSE)
##  [1] 4.300000 4.300000 4.471429 4.471429 4.642857 4.642857 4.814286 4.814286
##  [9] 4.985714 4.985714 5.157143 5.157143 5.328571 5.328571 5.500000 5.500000
sort(c(foo,bar,goo),decreasing=FALSE)
##  [1] 4.000000 4.300000 4.300000 4.471429 4.471429 4.642857 4.642857 4.814286
##  [9] 4.814286 4.985714 4.985714 5.157143 5.157143 5.328571 5.328571 5.500000
## [17] 5.500000
A2 <- seq(from=3,to=27,length.out=40)
D <- sort(c(goo,foo,bar,A2),decreasing=TRUE)

# Added Work
S <- rnorm(n=57,mean=11.92,sd=7.619811)
sort(S,decreasing=FALSE)
##  [1] -4.8545052 -2.9901345  0.9515861  3.7931505  3.8517234  4.4684472
##  [7]  5.0299672  5.0302821  5.6748823  5.9341523  6.0221383  6.0705834
## [13]  6.5274155  7.1526183  8.1075350  8.5685816  8.6026721  9.1111382
## [19] 10.3201617 10.4110891 10.5098164 10.6423887 10.7538559 11.3362728
## [25] 11.9833744 12.0169364 12.3062883 12.3501736 12.3541190 12.7589140
## [31] 12.8072753 12.8485861 14.0411821 14.0882706 14.4302827 14.5701619
## [37] 14.6139932 14.6968936 15.1988634 15.3732659 15.5291073 16.5601581
## [43] 17.0871082 17.8859431 19.1348821 19.6537128 19.8318847 20.1395689
## [49] 20.5169759 22.2072544 22.5677022 22.6258756 22.8736826 24.9670104
## [55] 25.6710580 25.9495125 26.0006346
log(S)
## Warning in log(S): NaNs produced
##  [1]         NaN  3.25812095  2.68763615  1.80345471  3.25615282  1.73604982
##  [7]  2.72122065  2.54623017  2.36484496  2.51398953  1.79544240  2.97826627
## [13]  2.37526438  2.66932897  2.98729098  1.61547607  2.88401510  1.96747849
## [19]  2.20949764  3.00268648  1.87601107  2.51367012  2.95151296  2.80699970
## [25]  2.55001339  2.55323377  2.42800756  2.64199459  2.34287150  2.64534258
## [31]  3.11909419  2.48631702  2.15207286  3.24536421  2.67897573  1.78072419
## [37]  2.68197951  2.33409943  2.51011038  2.74271616  3.02125264  1.33319694
## [43]  3.10041901  2.83832427         NaN  1.61541346  3.12998702  2.14810221
## [49]  2.09279388  2.35230972  2.48352022  2.73263002  1.34852069  3.21755537
## [55] -0.04962507  1.49704097  3.11651978
# Plotting
N <- seq_along(D)
plot(N,D,type="n",xlab="Azizi",ylab="Ayimo")

plot(S)

# Logs and exp
log(0.3)
## [1] -1.203973
log(0.3,base=2)
## [1] -1.736966
exp(-1.203973)
## [1] 0.2999999
# Save and load
save.image()
load(".Rdata")

# Factor example
ordfac.vec <- factor(
  c("small","Large","Large","Regular","Large"),
  levels=c("small","Regular","Large"),
  ordered=TRUE
)

# Arithmetic order example
X <- -5
X <- X+1

#Exercise 2.1
#(a)
a<-2.3
(6*a+42)/(3^(4.2-3.62))
## [1] 29.50556
#
#(b)i
(-4)^2+2
## [1] 18
#(ii)
-4^2+2
## [1] -14
#(iii)
(-4)^(2+2)
## [1] 256
#(iv)
-4^(2+2)
## [1] -256
#(c)
sqrt(((25.2+15+16.44+15.3+18.6)/5)*0.5)
## [1] 3.008987
#(d)
d<-log(0.3)

#(e)
exp(d)
## [1] 0.3
#(f)
print(-0.00000000423546322) #To see how R identify such a number in E-notation.
## [1] -4.235463e-09
# Exercise 2.2
t <- 3^2*4^(1/8)
z <- t/2.33
print(z)
## [1] 4.593504
m <- -8.2*10^(-13)
print(m)
## [1] -8.2e-13
print(z*m)
## [1] -3.766673e-12
# Example 2.3
Myvec <- c(1,3,1,42)
print(Myvec)
## [1]  1  3  1 42
foo <- 32.1
myvec2 <- c(3,-3,2,3.45,1e+03,64^0.5,2+(3-1.1)/9.44,foo)
print(myvec2)
## [1]    3.000000   -3.000000    2.000000    3.450000 1000.000000    8.000000
## [7]    2.201271   32.100000
myvec3 <- c(Myvec,myvec2)
print(myvec3)
##  [1]    1.000000    3.000000    1.000000   42.000000    3.000000   -3.000000
##  [7]    2.000000    3.450000 1000.000000    8.000000    2.201271   32.100000
# Exercise 2.3
myseqA <- seq(from=5,to=-11,by=-0.3)
rev(myseqA)
##  [1] -10.9 -10.6 -10.3 -10.0  -9.7  -9.4  -9.1  -8.8  -8.5  -8.2  -7.9  -7.6
## [13]  -7.3  -7.0  -6.7  -6.4  -6.1  -5.8  -5.5  -5.2  -4.9  -4.6  -4.3  -4.0
## [25]  -3.7  -3.4  -3.1  -2.8  -2.5  -2.2  -1.9  -1.6  -1.3  -1.0  -0.7  -0.4
## [37]  -0.1   0.2   0.5   0.8   1.1   1.4   1.7   2.0   2.3   2.6   2.9   3.2
## [49]   3.5   3.8   4.1   4.4   4.7   5.0
sort(myseqA,decreasing=TRUE)
##  [1]   5.0   4.7   4.4   4.1   3.8   3.5   3.2   2.9   2.6   2.3   2.0   1.7
## [13]   1.4   1.1   0.8   0.5   0.2  -0.1  -0.4  -0.7  -1.0  -1.3  -1.6  -1.9
## [25]  -2.2  -2.5  -2.8  -3.1  -3.4  -3.7  -4.0  -4.3  -4.6  -4.9  -5.2  -5.5
## [37]  -5.8  -6.1  -6.4  -6.7  -7.0  -7.3  -7.6  -7.9  -8.2  -8.5  -8.8  -9.1
## [49]  -9.4  -9.7 -10.0 -10.3 -10.6 -10.9
K <- rep(c(-1,3,-5,7,-9),time=2,each=10)
sort(K,decreasing=TRUE)
##   [1]  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  3  3  3  3  3
##  [26]  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
##  [51] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5
##  [76] -5 -5 -5 -5 -5 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9
J <- seq(6,12)
O <- rep(5.3,3)
T <- -3
P <- seq(102,100,length.out=9)
MyvectE <- c(J,O,T,P)
MyvectE
##  [1]   6.00   7.00   8.00   9.00  10.00  11.00  12.00   5.30   5.30   5.30
## [11]  -3.00 102.00 101.75 101.50 101.25 101.00 100.75 100.50 100.25 100.00
length(MyvectE)
## [1] 20
length(Myvec)
## [1] 4
foo <- Myvec[2]
Myvec[1]
## [1] 1
foo
## [1] 3
Myvec[length(Myvec)]
## [1] 42
myvec.len <- length(Myvec)
bar <- Myvec[myvec.len-1]
bar
## [1] 1
# Exercise 2.4
seq(3,6,length.out=5)
## [1] 3.00 3.75 4.50 5.25 6.00
z <- rep(c(2,-5.1,-33),times=2)
m <- (7/42)+2
v <- seq(3,6,length.out=5)
y <- v[1]
h <- z[1]
length(r<-m[1])
## [1] 1
length(y)
## [1] 1
length(z)
## [1] 6
length(v)
## [1] 5
tail(v,2)
## [1] 5.25 6.00
tail(m,1)
## [1] 2.166667
tail(z,1)
## [1] -33
r <- m[length(m)]
h <- z[length(z)]
h <- c(z[length(z)],z[1])
y <- c(v[length(v)],v[1])
f <- v[3:(length(v)-1)]
d <- z[3:(length(z)-1)]
q <- m[1:(length(m)-1)]
n <- seq(length(v),length(f),length.out=5)
u <- seq(length(z),length(d),length.out=5)
p <- seq(length(m),length(q),length.out=5)
w <- sort(v,decreasing=FALSE)
g <- sort(y,decreasing=FALSE)
b <- sort(m,decreasing=FALSE)
w[1:5]; g[2:1]; b[1:1]
## [1] 3.00 3.75 4.50 5.25 6.00
## [1] 6 3
## [1] 2.166667
sort(w,decreasing=TRUE)
## [1] 6.00 5.25 4.50 3.75 3.00
sort(g,decreasing=TRUE)
## [1] 6 3
sort(b,decreasing=TRUE)
## [1] 2.166667
# More sequence work
foo <- 5.3
bar <- foo:(-47.0+1.5)
print(bar)
##  [1]   5.3   4.3   3.3   2.3   1.3   0.3  -0.7  -1.7  -2.7  -3.7  -4.7  -5.7
## [13]  -6.7  -7.7  -8.7  -9.7 -10.7 -11.7 -12.7 -13.7 -14.7 -15.7 -16.7 -17.7
## [25] -18.7 -19.7 -20.7 -21.7 -22.7 -23.7 -24.7 -25.7 -26.7 -27.7 -28.7 -29.7
## [37] -30.7 -31.7 -32.7 -33.7 -34.7 -35.7 -36.7 -37.7 -38.7 -39.7 -40.7 -41.7
## [49] -42.7 -43.7 -44.7
A <- seq(from=3,to=27,by=3)
print(A)
## [1]  3  6  9 12 15 18 21 24 27
A2 <- seq(from=3,to=27,length.out=40)
print(A2)
##  [1]  3.000000  3.615385  4.230769  4.846154  5.461538  6.076923  6.692308
##  [8]  7.307692  7.923077  8.538462  9.153846  9.769231 10.384615 11.000000
## [15] 11.615385 12.230769 12.846154 13.461538 14.076923 14.692308 15.307692
## [22] 15.923077 16.538462 17.153846 17.769231 18.384615 19.000000 19.615385
## [29] 20.230769 20.846154 21.461538 22.076923 22.692308 23.307692 23.923077
## [36] 24.538462 25.153846 25.769231 26.384615 27.000000
myseq <- seq(from=foo,to=(-47.0+1.5),by=-2.4)
print(myseq)
##  [1]   5.3   2.9   0.5  -1.9  -4.3  -6.7  -9.1 -11.5 -13.9 -16.3 -18.7 -21.1
## [13] -23.5 -25.9 -28.3 -30.7 -33.1 -35.5 -37.9 -40.3 -42.7 -45.1
# Vector behavior
noo <- 5.5:0.5
noo
## [1] 5.5 4.5 3.5 2.5 1.5 0.5
noo-c(2,4,6,8,10,12)
## [1]   3.5   0.5  -2.5  -5.5  -8.5 -11.5
noo*c(1,-1,1,-1,1,-1)
## [1]  5.5 -4.5  3.5 -2.5  1.5 -0.5
mar <- c(1,-1)
noo*mar
## [1]  5.5 -4.5  3.5 -2.5  1.5 -0.5
qux <- 3
noo+qux
## [1] 8.5 7.5 6.5 5.5 4.5 3.5
noo+c(3)
## [1] 8.5 7.5 6.5 5.5 4.5 3.5
noo+rep(3,length(noo))
## [1] 8.5 7.5 6.5 5.5 4.5 3.5
noo[c(1,3,5,6)] <- c(-99,99)
noo
## [1] -99.0   4.5  99.0   2.5 -99.0  99.0
# Exercise 2.5
boo <- c(2,0.5,1,2,0.5,1,2,0.5,1)
boo <- boo/c(2,0.5,1)
boo
## [1] 1 1 1 1 1 1 1 1 1
vec <- rep(1,3)
c <- c(2,0.5,1)
var <- boo/c
var
## [1] 0.5 2.0 1.0 0.5 2.0 1.0 0.5 2.0 1.0
boo[1:length(boo)] <- vec
boo
## [1] 1 1 1 1 1 1 1 1 1
boo[length(boo)] <- c(rep(1,3))
## Warning in boo[length(boo)] <- c(rep(1, 3)): number of items to replace is not
## a multiple of replacement length
boo
## [1] 1 1 1 1 1 1 1 1 1
F <- c(45,77,20,19,101,120,212)
C <- (5/9)*(F-32)
C
## [1]   7.222222  25.000000  -6.666667  -7.222222  38.333333  48.888889 100.000000
moo <- rep(c(2,4,6),2)*rep(c(1,2),each=3)
moo
## [1]  2  4  6  4  8 12
moo[2:5] <- c(-0.1,-100)
moo
## [1]    2.0   -0.1 -100.0   -0.1 -100.0   12.0

Week 3

Monday 11th August 2025.

#Working with matrix command.
A<-matrix(data=c(-3,2,893,0.17),nrow=2,ncol=2)
A
##      [,1]   [,2]
## [1,]   -3 893.00
## [2,]    2   0.17
#Identical matrix
matrix(data=c(-3,2,893,0.17))
##        [,1]
## [1,]  -3.00
## [2,]   2.00
## [3,] 893.00
## [4,]   0.17
#Is the same as :
matrix(data=c(-3,2,893,0.17),nrow=4,ncol=1)
##        [,1]
## [1,]  -3.00
## [2,]   2.00
## [3,] 893.00
## [4,]   0.17
#Filling Direction
matrix(data=c(1,2,3,4,5,6),2,3,byrow=FALSE)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
#Now we change the direction by using "TRUE".
matrix(c(1,2,3,5,9,-0.5),2,3, TRUE)
##      [,1] [,2] [,3]
## [1,]    1    2  3.0
## [2,]    5    9 -0.5
#Row and Column Bindings
rbind(1:3,6:8)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    6    7    8
cbind(c(1,5),c(2,6),c(3,7))
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    5    6    7
#Matrix Dimension
mymat<-rbind(c(1,3,4),5:3,c(100,20,90),11:13)
mymat
##      [,1] [,2] [,3]
## [1,]    1    3    4
## [2,]    5    4    3
## [3,]  100   20   90
## [4,]   11   12   13
#To check dimension using "dim"
dim(mymat)
## [1] 4 3
nrow(mymat)
## [1] 4
ncol(mymat)
## [1] 3
dim(mymat)[2]
## [1] 3
#Sub-setting
B<-matrix(c(0.3,4.5,55.3,91,0.1,105.5,-4.2,8.2,27.9),nrow = 3,ncol = 3)
B
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  4.5   0.1  8.2
## [3,] 55.3 105.5 27.9
#Row,column,and Diagonal Extractions
B[,2] #This examines the second column.
## [1]  91.0   0.1 105.5
B[1,] #This examines the first row of the matrix.
## [1]  0.3 91.0 -4.2
#Using the Colon to indicate the values to be extracted.
B[2:3,]
##      [,1]  [,2] [,3]
## [1,]  4.5   0.1  8.2
## [2,] 55.3 105.5 27.9
B[,c(3,1)]
##      [,1] [,2]
## [1,] -4.2  0.3
## [2,]  8.2  4.5
## [3,] 27.9 55.3
# Adding arguments that can Work on the matrix.
B[c(3,1),2:3]
##       [,1] [,2]
## [1,] 105.5 27.9
## [2,]  91.0 -4.2
# identifying the values along the diagonal of a matrix.
diag(x=B)  #OR
## [1]  0.3  0.1 27.9
diag(B)
## [1]  0.3  0.1 27.9
# Omitting and Overwriting "Using the negative sign"
B[,-2]
##      [,1] [,2]
## [1,]  0.3 -4.2
## [2,]  4.5  8.2
## [3,] 55.3 27.9
# When I want to remove the first row and then Extracting Elements of B from 3:2
B[-1,3:2]
##      [,1]  [,2]
## [1,]  8.2   0.1
## [2,] 27.9 105.5
# The following removes the first row and second column of B.
B[-1,-2]
##      [,1] [,2]
## [1,]  4.5  8.2
## [2,] 55.3 27.9
B[-1,-c(2,3)]   # Delete first row, then second and the third columns respectively.
## [1]  4.5 55.3
#Overwriting an element, or entire rows or columns, you identify the elements to
#be replaced and then assign the new values.


C<-B
C
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  4.5   0.1  8.2
## [3,] 55.3 105.5 27.9
#Then following overwriting the second row of B
C[2,]<-1:3 #or  C[,2]<-1:3
C
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  1.0   2.0  3.0
## [3,] 55.3 105.5 27.9
C[c(1,3),2]<-900  #This means replace the first and third elements of C making
#sure it's on the second column with 900.

C
##      [,1] [,2] [,3]
## [1,]  0.3  900 -4.2
## [2,]  1.0    2  3.0
## [3,] 55.3  900 27.9
C[,3]<-C[3,]
C
##      [,1] [,2]  [,3]
## [1,]  0.3  900  55.3
## [2,]  1.0    2 900.0
## [3,] 55.3  900  27.9
# CONSIDERING Both row and column at the same time.
C[c(1,3),c(1,3)]<-c(-7,7)
C
##      [,1] [,2] [,3]
## [1,]   -7  900   -7
## [2,]    1    2  900
## [3,]    7  900    7
#Starting from column unto the rows assignes.
C[c(1,3),2:1]<-c(65,-65,88,-88)
C
##      [,1] [,2] [,3]
## [1,]   88   65   -7
## [2,]    1    2  900
## [3,]  -88  -65    7
#Changing the values of the diagonal of a matrix
diag(x=C)<-rep(0,3)
C
##      [,1] [,2] [,3]
## [1,]    0   65   -7
## [2,]    1    0  900
## [3,]  -88  -65    0

Tuesday 12th August 2025.

#Matrix operations and Algebra

#3.3.1 Matrix Transpose

S<-rbind(c(2,5,2),c(6,1,4))
t(S)
##      [,1] [,2]
## [1,]    2    6
## [2,]    5    1
## [3,]    2    4
S
##      [,1] [,2] [,3]
## [1,]    2    5    2
## [2,]    6    1    4
t(t(t(S)))
##      [,1] [,2]
## [1,]    2    6
## [2,]    5    1
## [3,]    2    4
#Identity matrix

A<-diag(3)   #Creates a square Identity matrix of 3 by 3 dimension.
A
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1
#Scalar multiple of a matrix
2*A  #Using a scalar say "x" to multiply a given vector say "A"
##      [,1] [,2] [,3]
## [1,]    2    0    0
## [2,]    0    2    0
## [3,]    0    0    2
2*S
##      [,1] [,2] [,3]
## [1,]    4   10    4
## [2,]   12    2    8
#Matrix addition and subtraction
D<-cbind(c(-2,3,6),c(8.1,8.2,-9.8))
E<-cbind(c(2,5,2),c(6,1,4))
E-D
##      [,1] [,2]
## [1,]    4 -2.1
## [2,]    2 -7.2
## [3,]   -4 13.8
#Matrix Multiplication
E<-rbind(c(2,5,2),c(6,1,4))
F<-cbind(c(3,-1,1),c(-3,1,5))
dim(E)
## [1] 2 3
dim(F)
## [1] 3 2
#They are compatible.
E%*%F
##      [,1] [,2]
## [1,]    3    9
## [2,]   21    3
F%*%E
##      [,1] [,2] [,3]
## [1,]  -12   12   -6
## [2,]    4   -4    2
## [3,]   32   10   22
#Note that Matrix multiplication is not commutative (i.e, when their positions
#changes the result to different values entirely).


#Inverse of a Matrix OR Matrix Inversion
A<-matrix(c(3,4,1,2),2,2)
A
##      [,1] [,2]
## [1,]    3    1
## [2,]    4    2
Q<-solve(A)   #The solve command is used to invert a matrix or simply to find the
#inverse of a Matrix.

#Verifying if the inverse is correct
A%*%Q   #Confirmed.
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
# Multidimensional Arrays

AR<-array(data=1:24,dim=c(3,4,2))
AR
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
#Note that (row,column,layer)
#Including the dimension of an array.
BR<-array(rep(1:24,3),dim=c(3,4,2,3))
BR
## , , 1, 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2, 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 1, 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2, 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 1, 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2, 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
#Note that (row,column,layer,blocks) connected to "dim'

#Subsets, Extractions, and Replacements
AR[2,,2]
## [1] 14 17 20 23
AR[2,c(3,1),2]
## [1] 20 14
# If I require only one output then:
AR[1,,]
##      [,1] [,2]
## [1,]    1   13
## [2,]    4   16
## [3,]    7   19
## [4,]   10   22
#and
BR[,,2,]
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
# When it has to do with two independent values.
BR[3:2,4,,]
## , , 1
## 
##      [,1] [,2]
## [1,]   12   24
## [2,]   11   23
## 
## , , 2
## 
##      [,1] [,2]
## [1,]   12   24
## [2,]   11   23
## 
## , , 3
## 
##      [,1] [,2]
## [1,]   12   24
## [2,]   11   23
BR[2,,1,]
##      [,1] [,2] [,3]
## [1,]    2    2    2
## [2,]    5    5    5
## [3,]    8    8    8
## [4,]   11   11   11
#Important Codes
#rbind
#cbind
#dim
#nrow
#ncol
#[ , ]
#diag
#t
#*
#  +,
#%*%
 # solve
#array.

#Exercise 3.1
#Solutions
#(a)
a<-matrix(c(4.3,3.1,8.2,8.2,3.2,0.9,1.6,6.5),4,2,byrow = TRUE)
a
##      [,1] [,2]
## [1,]  4.3  3.1
## [2,]  8.2  8.2
## [3,]  3.2  0.9
## [4,]  1.6  6.5
#(b)
dim(a[-1,])
## [1] 3 2
#(c)
a[,2]<-sort(a[,2],decreasing = FALSE)
a
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#(d)
matrix(a[-4,-1])
##      [,1]
## [1,]  0.9
## [2,]  3.1
## [3,]  6.5
a
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#(e)
d<-matrix(a[(3:4),],2,2)
d
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
#(f)
vals <- -(1/2) * diag(d)
a[4,2] <- vals[1]
a[1,2] <- vals[2]
a[4,1] <- vals[1]
a[1,1] <- vals[2]
a
##      [,1] [,2]
## [1,] -4.1 -4.1
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,] -1.6 -1.6
# Or
a[rbind(c(4,2),c(1,2),c(4,1),c(1,1))]<-(-(1/2)*diag(b))
a
##      [,1] [,2]
## [1,] -0.5  0.0
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  0.0 -0.5
a[c(4,1),c(2,1)]<- -(1/2)*diag(b)
a
##      [,1] [,2]
## [1,] -0.5  0.0
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  0.0 -0.5
#(a) #creating the vector
A<-matrix(c(4.3,3.1,8.2,8.2,3.2,0.9,1.6,6.5),4,2,byrow=T)
A
##      [,1] [,2]
## [1,]  4.3  3.1
## [2,]  8.2  8.2
## [3,]  3.2  0.9
## [4,]  1.6  6.5
#(b) #confirming the dimension
dim(A[-1,])
## [1] 3 2
#(c)
A[,2]<-sort(A[,2],decreasing = FALSE)
B<-A
B
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#(d)
matrix(B[-4,-1])
##      [,1]
## [1,]  0.9
## [2,]  3.1
## [3,]  6.5
#(e)
C<-B[c(3,4),]
C
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
B[c(length(B)-5,length(B)-4),]
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
B[c(3:4),]
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
B[-c(1:2),]
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
#(f)
B[c(4,1),c(2,1)]<--(1/2)*diag(C)
B
##      [,1] [,2]
## [1,] -4.1 -4.1
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,] -1.6 -1.6

Wednesday 13th August 2025.

#Non numeric values: Logical, Character and Factors.

#4.0 Logical
foo<-TRUE
foo
## [1] TRUE
bar<-FALSE
bar
## [1] FALSE
bar
## [1] FALSE
#Filling a vector with logical values.
baz<-c(T,F,F,F,T,F,T,T,T,F,T,F)
baz
##  [1] -3  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5 -3  3 -1  1 -3  1
## [26]  5 -3 -3 -3  3 -1  1 -3  1  5 -3  3 -1  1 -3  1  5
length(baz)
## [1] 42
#Creating matrix with logical data types.
qux<-matrix(baz,nrow = 3,ncol=4,byrow=foo)
## Warning in matrix(baz, nrow = 3, ncol = 4, byrow = foo): data length [42] is
## not a sub-multiple or multiple of the number of columns [4]
qux
##      [,1] [,2] [,3] [,4]
## [1,]   -3    3   -1    1
## [2,]   -3    1    5    3
## [3,]   -1    1   -3    1
#A Logical outcome: Relational operators
1==2
## [1] FALSE
1>2
## [1] FALSE
(2-1)<=2
## [1] TRUE
1!=(2+3)
## [1] TRUE
#Checking if the length of two different vectors are the same or not.
foo<-c(3,2,1,4,1,2,1,-1,0,3)
bar<-c(4,1,2,1,1,0,0,3,0,4)

#Checking
length(foo)==length(bar)
## [1] TRUE
#Consider the following evaluations
foo==bar  #Checking to see whether the are equal.
##  [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
foo<bar
##  [1]  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE
foo<=bar
##  [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE
foo<=(bar+10)
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#Recycling my Vectors
baz<-foo[c(10,3)]
baz
## [1] 3 1
foo<3
##  [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
#Let us now create a matrix with our objects
foo.mat<-matrix(foo,5,2)
foo.mat
##      [,1] [,2]
## [1,]    3    2
## [2,]    2    1
## [3,]    1   -1
## [4,]    4    0
## [5,]    1    3
bar.mat<-matrix(bar,5,2)
bar.mat
##      [,1] [,2]
## [1,]    4    0
## [2,]    1    0
## [3,]    2    3
## [4,]    1    0
## [5,]    1    4
#Comparing the two matrices with logical operators.
foo.mat<bar.mat
##       [,1]  [,2]
## [1,]  TRUE FALSE
## [2,] FALSE FALSE
## [3,]  TRUE  TRUE
## [4,] FALSE FALSE
## [5,] FALSE  TRUE
foo.mat<3
##       [,1]  [,2]
## [1,] FALSE  TRUE
## [2,]  TRUE  TRUE
## [3,]  TRUE  TRUE
## [4,] FALSE  TRUE
## [5,]  TRUE FALSE
#Forming a logical vector using the logical operators.
qux<-foo==bar
qux
##  [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
any(qux)
## [1] TRUE
all(qux)
## [1] FALSE
#Following the same rules
quux<-foo<=(bar+10)
quux
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
any(quux)
## [1] TRUE
all(quux)
## [1] TRUE
#Exercise 3.2
#Solutions
#(a)
(2/7)*((cbind(c(1,2,7),c(2,4,6)))-(cbind(c(10,30,50),c(20,40,60))))
##            [,1]       [,2]
## [1,]  -2.571429  -5.142857
## [2,]  -8.000000 -10.285714
## [3,] -12.285714 -15.428571
#(b)
A<-cbind(c(1,2,7))
B<-cbind(c(3,4,8))

#ii.
t(A)%*%B
##      [,1]
## [1,]   67
#iii.
t(B)%*%(A%*%t(A))
##      [,1] [,2] [,3]
## [1,]   67  134  469
#iv.
R<-(A%*%t(A))
T<-t(B)
#Not possible
#R*T
#(A%*%t(A))%*%t(B)


#v.
solve((B%*%t(B)+(A%*%t(A)-100*(diag(3)))))
##              [,1]         [,2]        [,3]
## [1,] -0.007923676  0.003123274 0.007843334
## [2,]  0.003123274 -0.005350239 0.011483806
## [3,]  0.007843334  0.011483806 0.017584735
#(c)
A<-(cbind(c(2,0,0,0),c(0,3,0,0),c(0,0,5,0),c(0,0,0,-1)))
A
##      [,1] [,2] [,3] [,4]
## [1,]    2    0    0    0
## [2,]    0    3    0    0
## [3,]    0    0    5    0
## [4,]    0    0    0   -1
(solve(A)%*%A)-diag(4) # Confirmed.
##      [,1] [,2] [,3] [,4]
## [1,]    0    0    0    0
## [2,]    0    0    0    0
## [3,]    0    0    0    0
## [4,]    0    0    0    0

Thursday 14th August 2025.

#Multiple Comparisons: Logical Operators
#FALSE||((T&&T)||FALSE)
!TRUE&&TRUE
## [1] FALSE
#(T&&(T||F))&&FALSE
(6<4)||(3!=1)
## [1] TRUE
#
(6<3)||(3!=1)||(9>1)
## [1] TRUE
#Element-wise examples
foo<-c(T,F,F,F,T,F,T,T,T,F,T,F)
foo
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8  3
## [26] -1  1 -3  1  5  3  4  8  3  4  8  3  4  8  3 -1  1 -3  1  5  3  4  8  3 -1
## [51]  1 -3  1  5
bar<-c(F,T,F,T,F,F,F,F,T,T,T,T)
bar
##  [1]  3 -1  1 -3  1  5  3  4  8  3 -1  1 -3  1  5  3  4  8  3 -1  1 -3  1  5  3
## [26] -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8  3  4  8  3  4
## [51]  8  3  4  8
#Comparing vector to vector element-wise
foo&bar # Using the short comparator.
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [46] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#Comparing vector to vector using the long comparator.
foo[1]&&bar[1]
## [1] TRUE
foo[1]||bar[1]
## [1] TRUE
#Exercise 3.3
#Solutions.
#(a)
A<-array(4.8:0.1,dim=c(4,2,6))
A
## , , 1
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  3.8  4.8
## [2,]  2.8  3.8
## [3,]  1.8  2.8
## [4,]  0.8  1.8
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1] [,2]
## [1,]  2.8  3.8
## [2,]  1.8  2.8
## [3,]  0.8  1.8
## [4,]  4.8  0.8
## 
## , , 6
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
#(b)
B<-A[c(4,1),2,]
B
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]  2.8  4.8  1.8  3.8  0.8  2.8
## [2,]  0.8  2.8  4.8  1.8  3.8  0.8
#(c)
C<-array(rep(B[2,],4),dim=c(2,2,2,3))
C
## , , 1, 1
## 
##      [,1] [,2]
## [1,]  0.8  4.8
## [2,]  2.8  1.8
## 
## , , 2, 1
## 
##      [,1] [,2]
## [1,]  3.8  0.8
## [2,]  0.8  2.8
## 
## , , 1, 2
## 
##      [,1] [,2]
## [1,]  4.8  3.8
## [2,]  1.8  0.8
## 
## , , 2, 2
## 
##      [,1] [,2]
## [1,]  0.8  4.8
## [2,]  2.8  1.8
## 
## , , 1, 3
## 
##      [,1] [,2]
## [1,]  3.8  0.8
## [2,]  0.8  2.8
## 
## , , 2, 3
## 
##      [,1] [,2]
## [1,]  4.8  3.8
## [2,]  1.8  0.8
#The first thing I did was to first check the dimension of B.
# so that I can find the appropriate argument for sub-setting.

#(d)
D<-A[,,-6]
D
## , , 1
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  3.8  4.8
## [2,]  2.8  3.8
## [3,]  1.8  2.8
## [4,]  0.8  1.8
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1] [,2]
## [1,]  2.8  3.8
## [2,]  1.8  2.8
## [3,]  0.8  1.8
## [4,]  4.8  0.8
D<-array(A,dim=c(4,2,(6-1)))
D
## , , 1
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  3.8  4.8
## [2,]  2.8  3.8
## [3,]  1.8  2.8
## [4,]  0.8  1.8
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1] [,2]
## [1,]  2.8  3.8
## [2,]  1.8  2.8
## [3,]  0.8  1.8
## [4,]  4.8  0.8
#(e)
D[c(2,4),2,c(1,3,5)]<--99
D
## , , 1
## 
##      [,1]  [,2]
## [1,]  4.8   0.8
## [2,]  3.8 -99.0
## [3,]  2.8   3.8
## [4,]  1.8 -99.0
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1]  [,2]
## [1,]  3.8   4.8
## [2,]  2.8 -99.0
## [3,]  1.8   2.8
## [4,]  0.8 -99.0
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1]  [,2]
## [1,]  2.8   3.8
## [2,]  1.8 -99.0
## [3,]  0.8   1.8
## [4,]  4.8 -99.0

Friday 15th August 2025.

#Logical Are Numbers!
TRUE+TRUE
## [1] 2
FALSE-TRUE  #PERFORMING ELEMENTARY NUMERIC OPERATIONS ON lOGICAL VALUES
## [1] -1
#T+T+F+T+F+F+T

#Substituting numerical values for logical values
1&&1
## [1] TRUE
1||0
## [1] TRUE
0&&1
## [1] FALSE
#Logical Sub-setting and Extraction.
myvec<-c(5,-2.3,4,4,4,6,8,10,40221,-8)
myvec[c(2,10)] #Or
## [1] -2.3 -8.0
#myvec[c(F,T,F,F,F,F,F,F,F,T)]
#Together the above code results to the negative vales. considering the
#The second code the values that are changed to be TRUTH  values are those that are extracted.

#Checking negative numeric values with logical relationals
myvec<0
##  [1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
#Sub-setting some certain values from a vector using logical ralation and numeric values
myvec[myvec<0]
## [1] -2.3 -8.0
#To extract the second values after the first values we use the :

#myvec[c(T,F)]

#And myvec[F,T] for second values beginning from the second term.
#More complicated extraction with relational and logical operators.
myvec[(myvec>0)&(myvec<100)]
## [1]  5  4  4  4  6  8 10
#Overwriting the values in the vector
myvec[myvec<0]<-(-200)
myvec
##  [1]     5  -200     4     4     4     6     8    10 40221  -200
#Changing Logical flags vector into numeric vectors with "which" function.

#which(x=c(T,F,F,T,T))

#Changing those values of myvec that satisfies the <0 criteria.
which(x=myvec<0)
## [1]  2 10
#To delete elements based on logical flags I can use the following:
myvec[-which(x=myvec<0)]
## [1]     5     4     4     4     6     8    10 40221
myvec[-which(x=myvec>0)]
## [1] -200 -200
#Exercise 4.1
#Solutions
#(a)
A<-c(6,9,7,3,6,7,9,6,3,6,6,7,1,9,1)

#To identify the above mention, we do:
#i.
A[A==6] #Those equal to 6
## [1] 6 6 6 6 6
#ii.
A[A>=6]  #Those greater than or equal to 6
##  [1] 6 9 7 6 7 9 6 6 6 7 9
#iii.
A[A<=(6+2)]  # Those less than 6+2
##  [1] 6 7 3 6 7 6 3 6 6 7 1 1
#iv.
A[A!=6]  # Those not equal to 6
##  [1] 9 7 3 7 9 3 7 1 9 1
#(b)
B<-c(A[-c(1:3)],dim=c(2,2,3))
B
##                                                             dim1 dim2 dim3 
##    3    6    7    9    6    3    6    6    7    1    9    1    2    2    3
#i. #Examining those less than or equal to 6/2 +4
B[B<=(6/2)+4]
##                                                   dim1 dim2 dim3 
##    3    6    7    6    3    6    6    7    1    1    2    2    3
#ii.
(B+2)[B<=(6/2)+4] #OR Q<-B+2
##                                                   dim1 dim2 dim3 
##    5    8    9    8    5    8    8    9    3    3    4    4    5
                 #Q[B<=(6/2)+4]

#(c)
C<-diag(10)  # Creating a 10by10 Identical matrix
which(C==0)  #identifying specific positions of values equal to 0
##  [1]  2  3  4  5  6  7  8  9 10 11 13 14 15 16 17 18 19 20 21 22 24 25 26 27 28
## [26] 29 30 31 32 33 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55
## [51] 57 58 59 60 61 62 63 64 65 66 68 69 70 71 72 73 74 75 76 77 79 80 81 82 83
## [76] 84 85 86 87 88 90 91 92 93 94 95 96 97 98 99
#(d)
any(B)  #Yes they are TRUE
## Warning in any(B): coercing argument of type 'double' to logical
## [1] TRUE
all(B)
## Warning in all(B): coercing argument of type 'double' to logical
## [1] TRUE
#(e)
R<-C[diag(C)]
any(R)
## Warning in any(R): coercing argument of type 'double' to logical
## [1] TRUE
#Exercise 4.2
#EXERCISE 4.2
#Solutions.

#(a) #To Identify elements >5 |==2
foo<-c(7,1,7,10,5,9,10,3,10,8)
foo[(foo>5)|(foo==2)]
## [1]  7  7 10  9 10 10  8
#a<-foo[(foo>5)|(foo==2)]
#(b)  #Identifying elements <=6&!=4
bar<-c(8,8,4,4,5,1,5,6,6,8)
bar[(bar<=6)&(bar!=4)]
## [1] 5 1 5 6 6
#b<-bar[(bar<=6)&(bar!=4)]
#(c)
#foo[a[1]]&&bar[b[1]]
#foo[1:(length(a)-2)]&bar[b]

#which((foo[a])&(bar[b]))  #This I assumed to be the answer.

#(d)
baz<-foo+bar
baz
##  [1] 15  9 11 14 10 10 15  9 16 16
#i.
baz[(baz>=14)&(baz!=15)]
## [1] 14 16 16
#ii.
c<-(baz/foo)
baz[((baz/foo)>4)|((baz/foo)<=2)]
## [1]  9 11 14 10 10 15 16 16
#c[(c>4)|(c<=2)]

#(e)
#c[(c>4)||(c<=2)]
#c[(c>4)&&(c<=2)]

Week 4

Monday 18th August 2025.

#Extraction of numeric values using logical values
A<-matrix(c(0.3,4.5,55.3,91,0.1,105.5,-4.2,8.2,27.9),nrow=3,ncol=3)
A
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  4.5   0.1  8.2
## [3,] 55.3 105.5 27.9
#To extract the second and third column elements of the first row of A, I can use or execute: A
A[1,2:3]  #OR
## [1] 91.0 -4.2
A[1,c(2,3)]
## [1] 91.0 -4.2
#But with logical values we can execute the following:

#A[c(T,F,F),c(F,T,T)]

#Logical flags application
A<1
##       [,1]  [,2]  [,3]
## [1,]  TRUE FALSE  TRUE
## [2,] FALSE  TRUE FALSE
## [3,] FALSE FALSE FALSE
A[A<1]<-(-7)
A
##      [,1]  [,2] [,3]
## [1,] -7.0  91.0 -7.0
## [2,]  4.5  -7.0  8.2
## [3,] 55.3 105.5 27.9
#Replacing values in a matrix using the index format alongside logical flags

#Finding the index position of elements in a matrix using logical flags.
A>25
##       [,1]  [,2]  [,3]
## [1,] FALSE  TRUE FALSE
## [2,] FALSE FALSE FALSE
## [3,]  TRUE  TRUE  TRUE
which(A>25)
## [1] 3 4 6 9
#Note that the which function in R is  mostly use to obtain the position of element in a vectoror matrx

#Checking this the other way round, because R count default column wise.
which(x=c(A[,1],A[,2],A[,3])>25)
## [1] 3 4 6 9
#Placing an array indexes TRUE or FALSE , in order to obtain the row and column index number of the element we seek their positions.
which(A>25, arr.ind=T)
## [1] 3 4 6 9
#section 4.2
#Creating a string
foo<-"This is a character string!"
foo
## [1] "This is a character string!"
length(foo)
## [1] 1
#Using "nchar" function to count the number of charecters in a string
nchar(foo)
## [1] 27
#String numeric characters are not the norminal numeric values, Hence this:
bar<-"23.3"
bar
## [1] "23.3"
#An attempt to multiply this value with a constant numeric value will only return an error.
#(bar*2)

#Comparing string values
"alpha"=="alpha"
## [1] TRUE
"alpha"!="beta"
## [1] TRUE
c("alpha","beta","gamma")=="beta"
## [1] FALSE  TRUE FALSE
#Other comparison
"gamma">"Alpha"
## [1] TRUE
#Considering lowercase vs. uppercase
"Alpha">"alpha"
## [1] TRUE
"beta">="bEtA"
## [1] FALSE
#Using special characters
baz<-"&4_3**%?$ymbolic non$en$e,;"
baz
## [1] "&4_3**%?$ymbolic non$en$e,;"
#Use the "cat" and "paste" functions.
qux<-c("awesome","R","is")
length(qux)
## [1] 3
qux
## [1] "awesome" "R"       "is"
#Calling "cat" or "paste" functions.
cat(qux[2],qux[3],"totally",qux[1],"!")
## R is totally awesome !
paste(qux[2],qux[3],"totally",qux[1],"!")
## [1] "R is totally awesome !"
#Want to separate using the "sep" function.
paste(qux[2],qux[3],"totally",qux[1],"!",sep="---")
## [1] "R---is---totally---awesome---!"
paste(qux[2],qux[3],"totally",qux[1],"!",sep="")
## [1] "Ristotallyawesome!"
#Using manual insertion of spacing where necessary.
cat("Do yo think ",qux[2]," ",qux[3]," ",qux[1],"?",sep="")
## Do yo think R is awesome?
#Passing many R objects with the "cat" and "paste" function as an object.
a<-3
b<-4.4
cat("The value stored as 'a' is ",a,".",sep="")
## The value stored as 'a' is 3.
paste("The value stored as 'b' is ",b,".",sep="")
## [1] "The value stored as 'b' is 4.4."
#Performing some little clculations
cat("The result of a+b is ",a,"+",b,"=",a+b,".",sep="")
## The result of a+b is 3+4.4=7.4.
paste("Is ",a+b," less than 10? That's totally ",a+b<10,".",sep="")
## [1] "Is 7.4 less than 10? That's totally TRUE."
#Spacing using the escape sequence.
cat("here is a string\nsplit\tto new\b\n\n\tlines")
## here is a string
## split    to new
## 
##  lines
#Using the escape signal to inculcate the backslash and the quotation sign.
cat("I really want a backslash: \\\nand a double quote: \"")
## I really want a backslash: \
## and a double quote: "
cat("I would love to have a double backslash:\\\nand a qoute:\"")
## I would love to have a double backslash:\
## and a qoute:"
cat("Mr Ade said, \"He lost his father on Wednesday\" \nbut the Principal couldn't allow him to go home that very day.\n What a tragedy!")
## Mr Ade said, "He lost his father on Wednesday" 
## but the Principal couldn't allow him to go home that very day.
##  What a tragedy!
#Note the following:
#(\n, \b, \t, \", and \\).

#setwd("/folder1/folder2/folder3/")


#Using the function "substr" to extract some certain values of choice.
foo<-"This is a character string!"
foo
## [1] "This is a character string!"
substr(foo,21,27)
## [1] "string!"
#Replacing extracted values
substr(foo,1,4)<-"Here"

#Substitution with "sub" and "gsub" function.
bar<-"How much wood could a woodchuck chuck"
sub(pattern="chuk",replacement="hurl",x=bar)
## [1] "How much wood could a woodchuck chuck"
gsub(pattern="chuck",replacement = "hurl",x=bar)
## [1] "How much wood could a woodhurl hurl"
cat("Martha ","sat ","at the foot of ","Jesus ","only to hear Him speak to her",sep="")
## Martha sat at the foot of Jesus only to hear Him speak to her

Tuesday 19th August 2025.

#Exercise 4.3
#(Solutions).
#(a)
#Storing the vectors as provided.
#i.
foo<-c(7,5,6,1,2,10,8,3,8,2)
bar<-(foo[(foo>=5)])
bar
## [1]  7  5  6 10  8  8
#ii.
foo[(-(foo>=5))]
## [1]  5  6  1  2 10  8  3  8  2
#(b)
#i.
baz<-matrix(bar,2,3,byrow=T)
baz
##      [,1] [,2] [,3]
## [1,]    7    5    6
## [2,]   10    8    8
#ii.
a<-sqrt(baz[1,2])
a
## [1] 2.236068
baz[baz==8]<-a
baz
##      [,1]     [,2]     [,3]
## [1,]    7 5.000000 6.000000
## [2,]   10 2.236068 2.236068
#ii.
#Confirming that all values in baz are <=25 and grater than 4
baz[(baz<=25)&(baz>4)]
## [1]  7 10  5  6
#(c)
#i.
qux<-array(c(10,5,1,4,7,4,3,3,1,3,4,3,1,7,8,3,7,3),dim=c(3,2,3))
which(qux==(3||4),arr.ind = T)
## [1]  3  9 13
#ii.
qux[(qux<3)|(qux>=7)]<-100
qux
## , , 1
## 
##      [,1] [,2]
## [1,]  100    4
## [2,]    5  100
## [3,]  100    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    3    3
## [2,]    3    4
## [3,]  100    3
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  100    3
## [2,]  100  100
## [3,]  100    3
#(d)
#foo[c(F,T)]

#Trying to see whether 0 and 1 can work in this case
foo[c(0,1)]
## [1] 7
#WE cannot!
#Logical values is repeated over the given elements evenly. while numeric argument for indexing 0,1 extracts only the first appoint value. Thats why in this case R picks the second argument and ignore the first argument because it is 0.

Wednesday 20th September 2025.

#Section 4.3
#Factors
firstname<-c("Liz","Jolene","Susan","Boris","Rochelle","Tim","Simon","Amy")
sex.num<-c(0,0,0,1,0,1,1,0)
sex.char<-c("female","female","female","male","female","male","male","female")

#Creating a factor vector using the "factor" function.
sex.num.fac<-factor(x=sex.num)
sex.num.fac
## [1] 0 0 0 1 0 1 1 0
## Levels: 0 1
sex.char.fac<-factor(sex.char)
sex.char.fac
## [1] female female female male   female male   male   female
## Levels: female male
#Extracting the levels of a factor vector
levels(x=sex.num.fac)
## [1] "0" "1"
levels(x=sex.char.fac)
## [1] "female" "male"
#Relabeling the factor using "levels" function.
levels(x=sex.num.fac)<-c("1","2")
sex.num.fac
## [1] 1 1 1 2 1 2 2 1
## Levels: 1 2
#Sub-setting
sex.char.fac[2:5]
## [1] female female male   female
## Levels: female male
sex.char.fac[c(1:3,5,8)]
## [1] female female female female female
## Levels: female male
sex.char.fac
## [1] female female female male   female male   male   female
## Levels: female male
#Using Logical flags on factor.
sex.num.fac=="2"   #Note that you must use string (quotation mark) to identify the numeric levels of a factor.
## [1] FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE
#Using Logical flags to obtain certain values from two or more factor vector.
firstname[sex.char.fac=="male"]
## [1] "Boris" "Tim"   "Simon"
firstname[sex.char.fac=="female"]
## [1] "Liz"      "Jolene"   "Susan"    "Rochelle" "Amy"
firstname[sex.char=="female"]
## [1] "Liz"      "Jolene"   "Susan"    "Rochelle" "Amy"
firstname[sex.num=="1"]
## [1] "Boris" "Tim"   "Simon"
firstname[sex.num=="0"]
## [1] "Liz"      "Jolene"   "Susan"    "Rochelle" "Amy"
#Defining and Ordering Levels
mob<-c("Apr","Jan","Dec","Sep","Nov","Jul","Jul","Jun")
mob[2]
## [1] "Jan"
mob[3]
## [1] "Dec"
mob[2]<mob[3]
## [1] FALSE
#Defining levels in details now: Using the "levels" and "ordered" function respectively.
ms<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
#mob.fac<-factor(x=mob,levels=ms,ordered = TRUE)
#mob.fac

#Performing Relational comparison
#mob.fac[2]
#mob.fac[3]

# And again
#(mob.fac[2])<(mob.fac[3])
#Combing and cutting
foo<-c(5.1,3.3,3.1,4)
bar<-c(4.5,1.2)
c(foo,bar)
## [1] 5.1 3.3 3.1 4.0 4.5 1.2
#Another format
#new.values<-factor(x=c("Oct","Feb","Feb"),levels=levels(mob.fac),ordered=TRUE)
#new.values

#Now combining the two vectors together.
#c(mob.fac,new.values)

#Checking the index of each month
#levels(mob.fac)

#Extraction
#levels(mob.fac)[c(mob.fac,new.values)]
#mob.new<-levels(mob.fac)[c(mob.fac,new.values)]
#mob.new.fac<-factor(x=mob.new,levels = levels(mob.fac),ordered = TRUE)
#mob.new.fac

#Taking an Example
Y<-c(0.53,5.4,1.5,3.33,0.45,0.01,2,4.2,1.99,1.01)

#Using the "cut" to give intervals to the values in a vector.
br<-c(0,2,4,6)
cut(x=Y,breaks=br)
##  [1] (0,2] (4,6] (0,2] (2,4] (0,2] (0,2] (0,2] (4,6] (0,2] (0,2]
## Levels: (0,2] (2,4] (4,6]
#Setting the boundaries axis , making the upper bound be at the left.

#cut(x=Y,breaks=br,right=FALSE)
#cut(x=Y,breaks=br,right=FALSE,include.lowest=T)

#Including a label with "labels" function
lab<-c("Small","Medium","Large")
#cut(x=Y,breaks=br,right=F,include.lowest=T,labels=lab)

Thursday 21st August 2025.

#Exercise 4.4
#(#Solution
#(a)
#cat("\"The quick brown fox \n\tjumped over\n\t\tthe lazy dogs\"")

#(b)
#Returning a written values with objects registered on R
num1<-4
num2<-0.75
paste("The result of multiplying",num1,"by",num2,"is",num1*num2)
## [1] "The result of multiplying 4 by 0.75 is 3"
#(c)
Path<-("C:/Users/hp/OneDrive/Documents/ICAMMDA/3rd Week of my IT/")
gsub("hp","JAlushi",Path)
## [1] "C:/Users/JAlushi/OneDrive/Documents/ICAMMDA/3rd Week of my IT/"
#Substituting "hp"

#(d)
#i.
bar<-"How much wood could a woodchucks chuck"
substr(bar,1,nchar(bar))<-"if a woodchuck could chuck wood"
bar
## [1] "if a woodchuck could chuck woods chuck"
#ii.
gsub("wood","metal",bar)
## [1] "if a metalchuck could chuck metals chuck"
#(e)
Storestr<-"Two 6-packs for $12.99"
#i.
substr(Storestr,5,10)
## [1] "6-pack"
#ii.
gsub("12.99","10.99",Storestr)
## [1] "Two 6-packs for $10.99"

Friday 22nd August 2025.

#Chapter 5
#An Introduction to the List and Data Frame
#foo<-list(matrix(data=1:4,nrow=2,ncol=2),c(T,F,T,T),"hello","Mark Abdul")
#foo

#Checking the numbers of object in a list using the "length" function.
#length(foo)


#Exercise 4.5
#Solutions
Pol.party<-c("National","Labour","Greens","Maori","Other")
A<-(1:20)
num.females<-c(1,5:7,12,14:16)
num.males<-A[-(num.females)]
Labour<-c(1,4,12,15,16,19)
Maori<-c()
Greens<-c(6,9,11)
Other<-c(10,20)
National<-c(2,3,5,7,8,13,14,17,18)

A[Labour]<-"Labour"
A[Greens]<-"Greens"
A[Other]<-"Other"
A[National]<-"National"
A
##  [1] "Labour"   "National" "National" "Labour"   "National" "Greens"  
##  [7] "National" "National" "Greens"   "Other"    "Greens"   "Labour"  
## [13] "National" "National" "Labour"   "Labour"   "National" "National"
## [19] "Labour"   "Other"
#(a)
sex<-rep("M",20)
sex[num.females]<-"F"
sex
##  [1] "F" "M" "M" "M" "F" "F" "F" "M" "M" "M" "M" "F" "M" "F" "F" "F" "M" "M" "M"
## [20] "M"
party<-A

#(b)
sex.factor<-factor(x=sex,ordered=TRUE)
sex.factor
##  [1] F M M M F F F M M M M F M F F F M M M M
## Levels: F < M
party.factor<-factor(x=party,ordered=TRUE)
party.factor
##  [1] Labour   National National Labour   National Greens   National National
##  [9] Greens   Other    Greens   Labour   National National Labour   Labour  
## [17] National National Labour   Other   
## Levels: Greens < Labour < National < Other
#Yes because R tends to arrange the Levels by specifying which one is less than the other.

#(c)
#i.
party.factor[(sex.factor=="F")]
## [1] Labour   National Greens   National Labour   National Labour   Labour  
## Levels: Greens < Labour < National < Other
#ii.
sex.factor[party.factor=="National"]
## [1] M M F F M M F M M
## Levels: F < M
#(d)
#i.
new.party_factor<-c(party.factor,c("National","Maori","Maori","Labour","Greens","Labour"))
new.party_factor
##  [1] "2"        "3"        "3"        "2"        "3"        "1"       
##  [7] "3"        "3"        "1"        "4"        "1"        "2"       
## [13] "3"        "3"        "2"        "2"        "3"        "3"       
## [19] "2"        "4"        "National" "Maori"    "Maori"    "Labour"  
## [25] "Greens"   "Labour"
new.sex_factor<-c(sex.factor,c("M","M","F","F","F","M"))
new.sex_factor
##  [1] "1" "2" "2" "2" "1" "1" "1" "2" "2" "2" "2" "1" "2" "1" "1" "1" "2" "2" "2"
## [20] "2" "M" "M" "F" "F" "F" "M"
#ii.
result<-c(93,55,29,100,52,84,56,0,33,52,35,53,55,46,40,40,56,45,64,31,10,29,40,95,18,61)

#(e)
br<-c(0,30,70,100)
lab<-c("Low","Moderate","High")
B<-cut(x=result,breaks = br,right = FALSE,include.lowest = TRUE,labels =lab )

#(f)
B[new.party_factor=="Labour"]
## [1] High     Moderate
## Levels: Low Moderate High
B[new.party_factor=="National"]
## [1] Low
## Levels: Low Moderate High
#I noticed that after extraction Labour party tends to have (High and Moderate) confidence level but on the other hand National party yielded only Low confidence level.

Week 5

ICMSO Conference.

Week 6

Monday 1st September 2025.

#Retrieving components from a list using the known Indexes format,but now  now entered in double bracket.
#Recall that we used the following:
  foo<-list(matrix(1:4,2,2),c(T,F,T,T),"hello")
foo
## [[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## [[2]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## [[3]]
## [1] "hello"
#Extraction
foo[[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
foo[[3]]
## [1] "hello"
#Member referencing
foo[[1]]+5.5
##      [,1] [,2]
## [1,]  6.5  8.5
## [2,]  7.5  9.5
#Extracting the first and second (row and column) of a  matrix
foo[[1]][1,2]
## [1] 3
foo[[1]][2,]
## [1] 2 4
#Adding a set of character values.
cat(foo[[3]],"you!")
## hello you!
foo[[3]]
## [1] "hello"
foo[[3]]<-paste(foo[[3]],"you!")
foo
## [[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## [[2]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## [[3]]
## [1] "hello you!"
#Accessing some components of foo (Accessing the 2 and 3 components of foo)
foo[[c(2,3)]]
## [1] 8
#List slicing (We use only a single square bracket)
bar<-foo[c(2,3)]
bar
## [[1]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## [[2]]
## [1] "hello you!"
#This results to the 2 and 3rd component in the list environs
#Note: the "bar" also denotes a new list with two components.


#5.1.2 Naming of components in a list
names(foo)<-c("mymatrix","mylogicals","mystring")
foo
## $mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $mystring
## [1] "hello you!"
baz<-list(array(1:20,c(2,2,5)),"Amina is coming tomorrow",c(T,F,F,F,T),"Andrews")
baz
## [[1]]
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## [[2]]
## [1] "Amina is coming tomorrow"
## 
## [[3]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## [[4]]
## [1] "Andrews"
names(baz)<-c("Numeric array","Wife","Logicals","Husband")
baz
## $`Numeric array`
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## $Wife
## [1] "Amina is coming tomorrow"
## 
## $Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## $Husband
## [1] "Andrews"
#Extraction with specific names
baz$Husband
## [1] "Andrews"
baz$Wife
## [1] "Amina is coming tomorrow"
baz$Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
#More on extraction
foo[[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
#more on extraction
foo[[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
baz[[1]]
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
#Sub-setting named members also works the same way
all(baz$"Numerical array"[,2,]==baz[[1]][,2,])
## [1] TRUE
#The above code show me that the comparison is TRUE.

#Assigning a label to each component
bar<-list(tom=c(foo[[2]],T,T,T,F),dick="g'day mate",harry=foo$mymatrix*2)
bar
## $tom
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8  3  4  8  3  4  8  3  4  8  3
## [26] -1  1 -3  1  5
## 
## $dick
## [1] "g'day mate"
## 
## $harry
##      [,1] [,2]
## [1,]    2    6
## [2,]    4    8
#To check the objects name using the "names" function
names(bar)
## [1] "tom"   "dick"  "harry"
#When using the names function, the component names are always provided and
#(returned as character strings in double quotes. However, if you’re specifying names
#when a list is created (inside the list function) or using names to extract members
#with the dollar operator, the names are entered without quotes (in other words, they
#                                                                are not given as strings)

Tuesday 2nd September 2025.

#Nesting:
  baz$bobby<-foo
baz
## $`Numeric array`
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## $Wife
## [1] "Amina is coming tomorrow"
## 
## $Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## $Husband
## [1] "Andrews"
## 
## $bobby
## $bobby$mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $bobby$mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $bobby$mystring
## [1] "hello you!"
foo$bobby<-baz
foo
## $mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $mystring
## [1] "hello you!"
## 
## $bobby
## $bobby$`Numeric array`
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## $bobby$Wife
## [1] "Amina is coming tomorrow"
## 
## $bobby$Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## $bobby$Husband
## [1] "Andrews"
## 
## $bobby$bobby
## $bobby$bobby$mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $bobby$bobby$mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $bobby$bobby$mystring
## [1] "hello you!"
baz$bobby$mylogicals[1:3]
## [1] 3 4 8
#More
baz[[5]][[2]][1:3]
## [1] 3 4 8
baz[[5]]$mylogicals[1:3]
## [1] 3 4 8
#Requesting for the first three elements of the component of a list.

Wednesday 3rd September 2025.

#Exercise 5.1
#(a)
a<-seq(-4,4,length.out=20)
b<-matrix(c(F,T,T,T,F,T,T,F,F),3,3)
## Warning in matrix(c(F, T, T, T, F, T, T, F, F), 3, 3): data length differs from
## size of matrix: [39 != 3 x 3]
c<-c("don","quixote")
d<-factor(c("LOW","MED","LOW","MED","MED","HIGH"))

#Creating a list
var<-list(seq(-4,4,length.out=20),matrix(c(F,T,T,T,F,T,T,F,F),3,3),c("don","quixote"),factor(c("LOW","MED","LOW","MED","MED","HIGH")))
## Warning in matrix(c(F, T, T, T, F, T, T, F, F), 3, 3): data length differs from
## size of matrix: [39 != 3 x 3]
names(var)<-c("Numericals","Logical matrix","String character","factor")

#Extracting
#(i)
var$`Logical matrix`[c(2,1),c(2,3)]
##      [,1] [,2]
## [1,]    1    4
## [2,]   -3    3
cat(var$`String character`)
## don quixote
#(ii)
M<-sub(pattern="quixote",replacement = "Quixote",x=var)
M
## [1] "c(-4, -3.57894736842105, -3.15789473684211, -2.73684210526316, -2.31578947368421, -1.89473684210526, -1.47368421052632, -1.05263157894737, -0.631578947368421, -0.210526315789474, 0.210526315789473, 0.631578947368421, 1.05263157894737, 1.47368421052632, 1.89473684210526, 2.31578947368421, 2.73684210526316, 3.1578947368421, 3.57894736842105, 4)"
## [2] "c(3, -1, 1, -3, 1, 5, 3, 4, 8)"                                                                                                                                                                                                                                                                                                                          
## [3] "c(\"don\", \"Quixote\")"                                                                                                                                                                                                                                                                                                                                 
## [4] "c(2, 3, 2, 3, 3, 1)"
M<-sub(pattern="don",replacement = "Don",x=M)
M
## [1] "c(-4, -3.57894736842105, -3.15789473684211, -2.73684210526316, -2.31578947368421, -1.89473684210526, -1.47368421052632, -1.05263157894737, -0.631578947368421, -0.210526315789474, 0.210526315789473, 0.631578947368421, 1.05263157894737, 1.47368421052632, 1.89473684210526, 2.31578947368421, 2.73684210526316, 3.1578947368421, 3.57894736842105, 4)"
## [2] "c(3, -1, 1, -3, 1, 5, 3, 4, 8)"                                                                                                                                                                                                                                                                                                                          
## [3] "c(\"Don\", \"Quixote\")"                                                                                                                                                                                                                                                                                                                                 
## [4] "c(2, 3, 2, 3, 3, 1)"
M$`String character`<-M[[3]]
## Warning in M$`String character` <- M[[3]]: Coercing LHS to a list
var
## $Numericals
##  [1] -4.0000000 -3.5789474 -3.1578947 -2.7368421 -2.3157895 -1.8947368
##  [7] -1.4736842 -1.0526316 -0.6315789 -0.2105263  0.2105263  0.6315789
## [13]  1.0526316  1.4736842  1.8947368  2.3157895  2.7368421  3.1578947
## [19]  3.5789474  4.0000000
## 
## $`Logical matrix`
##      [,1] [,2] [,3]
## [1,]    3   -3    3
## [2,]   -1    1    4
## [3,]    1    5    8
## 
## $`String character`
## [1] "don"     "quixote"
## 
## $factor
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
d<-M[[3]]
d
## [1] "c(\"Don\", \"Quixote\")"
d <- "Don Quixote"

cat("Windmills! ATTACK!", "\n\t-\\",d,"/-\n")
## Windmills! ATTACK! 
##  -\ Don Quixote /-
#(iii)
var$Numericals[var$Numericals>1]
## [1] 1.052632 1.473684 1.894737 2.315789 2.736842 3.157895 3.578947 4.000000
#(iv)
which(var$factor=="MED")
## [1] 2 4 5
#(b)
bar<-list(var$factor,c(3,2.1,3.3,4,1.5,4.9),var[(1:3)])
names(bar)<-c("facs","nums","oldlist")
bar
## $facs
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
## 
## $nums
## [1] 3.0 2.1 3.3 4.0 1.5 4.9
## 
## $oldlist
## $oldlist$Numericals
##  [1] -4.0000000 -3.5789474 -3.1578947 -2.7368421 -2.3157895 -1.8947368
##  [7] -1.4736842 -1.0526316 -0.6315789 -0.2105263  0.2105263  0.6315789
## [13]  1.0526316  1.4736842  1.8947368  2.3157895  2.7368421  3.1578947
## [19]  3.5789474  4.0000000
## 
## $oldlist$`Logical matrix`
##      [,1] [,2] [,3]
## [1,]    3   -3    3
## [2,]   -1    1    4
## [3,]    1    5    8
## 
## $oldlist$`String character`
## [1] "don"     "quixote"
#(i)
bar$facs[bar$nums>=3]
## [1] LOW  LOW  MED  HIGH
## Levels: HIGH LOW MED
#(ii)
bar$flags<-rep(bar$oldlist$`Logical matrix`[,3],2)
bar$flags
## [1] 3 4 8 3 4 8
#(iii)
bar$nums[!bar$flags]
## numeric(0)
#(iv)
bar$oldlist$`String character`<-"Don Quixote"
R<-cat(bar$oldlist$`String character`)
## Don Quixote
bar
## $facs
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
## 
## $nums
## [1] 3.0 2.1 3.3 4.0 1.5 4.9
## 
## $oldlist
## $oldlist$Numericals
##  [1] -4.0000000 -3.5789474 -3.1578947 -2.7368421 -2.3157895 -1.8947368
##  [7] -1.4736842 -1.0526316 -0.6315789 -0.2105263  0.2105263  0.6315789
## [13]  1.0526316  1.4736842  1.8947368  2.3157895  2.7368421  3.1578947
## [19]  3.5789474  4.0000000
## 
## $oldlist$`Logical matrix`
##      [,1] [,2] [,3]
## [1,]    3   -3    3
## [2,]   -1    1    4
## [3,]    1    5    8
## 
## $oldlist$`String character`
## [1] "Don Quixote"
## 
## 
## $flags
## [1] 3 4 8 3 4 8

Thursday 4th September 2025.

Review Class.

2+3
## [1] 5
sqrt(9)
## [1] 3
2*5
## [1] 10
((0.44*(1-0.44))/34)^(1/2)
## [1] 0.08512966
log(225,15)
## [1] 2
#Solving a particular problem.
a=2.3
(6*a+42)/(3^(4.2-3.62))
## [1] 29.50556
#Another problem
(-4)^2+2
## [1] 18
-4^2+2
## [1] -14
(-4)^(2+2)
## [1] 256
-4^(2+2)
## [1] -256
log(3,exp(1))
## [1] 1.098612
#Assignment
x=10
mynumber=45.5
y=mynumber*x
y
## [1] 455
#Create an object that stores the value 32 418.
#b. Overwrite your object in (a) by itself divided by 2.33. Print the
#result to the console.
#c.
#Create a new object with the value 82 10 13.
#d. Print directly to the console the result of multiplying (b) by (c).

#(a)
vicka<-3^2*(4^(1/8))
vicka
## [1] 10.70286
#(b)
vicka<-vicka/2.33   #Overwriting
vicka
## [1] 4.593504
#(c)
vicka1<--8.2*10^(-13)
vicka1
## [1] -8.2e-13
#(d)
vicka*vicka1
## [1] -3.766673e-12

Friday 5th September 2025.

mydata<-data.frame(person=c("Peter","Lois","Meg","Chris","Stewie"),
                   age=c(42,40,17,14,1),
                   sex=factor(c("M","F","F","M","M")))
mydata
##   person age sex
## 1  Peter  42   M
## 2   Lois  40   F
## 3    Meg  17   F
## 4  Chris  14   M
## 5 Stewie   1   M
#Extracting portion of data
mydata[2,2]
## [1] 40
mydata[3:5,3]
## [1] F M M
## Levels: F M
#Extraction in a certain order
mydata[,c(3,1)]
##   sex person
## 1   M  Peter
## 2   F   Lois
## 3   F    Meg
## 4   M  Chris
## 5   M Stewie
#using the dollar sign to extract a member of the object passed to data.frame.
mydata$age
## [1] 42 40 17 14  1
#Sub-setting this returned vector too, we do:
mydata$age[2]
## [1] 40
#In data-frame column stands for "variables" and the row stands for "Records".

#Reporting the size of a data-frame.
nrow(mydata)
## [1] 5
ncol(mydata)
## [1] 3
dim(mydata)
## [1] 5 3
#R default set character variables to vector as thus:
mydata$person
## [1] "Peter"  "Lois"   "Meg"    "Chris"  "Stewie"
#Adding Data Columns and Combining Data Frames.
newrecord<-data.frame(person="Brain",age=7,
  sex=factor("M",levels = levels(mydata$sex)))

newrecord
##   person age sex
## 1  Brain   7   M
#Now I can put the new record into the old data frame record list.
mydata<-rbind(mydata,newrecord)
mydata
##   person age sex
## 1  Peter  42   M
## 2   Lois  40   F
## 3    Meg  17   F
## 4  Chris  14   M
## 5 Stewie   1   M
## 6  Brain   7   M
#Adding a column (Variable)
funny<-c("High","High","Low","Med","High","Med")
funny<-factor(funny,levels=c("Low","Med","High"))
funny
## [1] High High Low  Med  High Med 
## Levels: Low Med High
#Now add the column that is (variables)
mydata<-cbind(mydata,funny)
mydata
##   person age sex funny
## 1  Peter  42   M  High
## 2   Lois  40   F  High
## 3    Meg  17   F   Low
## 4  Chris  14   M   Med
## 5 Stewie   1   M  High
## 6  Brain   7   M   Med
#Adding a new colum with the dollar sign
mydata$age.mom<-mydata$age*12
mydata
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 2   Lois  40   F  High     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
## 6  Brain   7   M   Med      84
#Logical Record Subset
#Examining all records corresponding to males ~ "mydata"
mydata$sex=="M"  #Identifying relevant position
## [1]  TRUE FALSE FALSE  TRUE  TRUE  TRUE
#Now getting all the record that pertain the data.frame
mydata[mydata$sex=="M",]
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
## 6  Brain   7   M   Med      84
#Removing a certain column (variable)
mydata[mydata$sex=="M",-3]
##   person age funny age.mom
## 1  Peter  42  High     504
## 4  Chris  14   Med     168
## 5 Stewie   1  High      12
## 6  Brain   7   Med      84
#Now If I want to extract certain variables with conditions.
mydata[mydata$sex=="M",c("person","age","funny","age.mom")]
##   person age funny age.mom
## 1  Peter  42  High     504
## 4  Chris  14   Med     168
## 5 Stewie   1  High      12
## 6  Brain   7   Med      84
#Extracting the full records for individuals who are more than 10years old OR have a high degree of funniness
mydata[mydata$age>10|mydata$funny=="High",]
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 2   Lois  40   F  High     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
#Check this out:
mydata[mydata$age<45,] #but with
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 2   Lois  40   F  High     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
## 6  Brain   7   M   Med      84
mydata[mydata$age>45,] #Yields an empty result
## [1] person  age     sex     funny   age.mom
## <0 rows> (or 0-length row.names)

Week 7

Monday 8th september 2025.

#Exercise 5.2
#(a)
#Creating and storing some set of data as dframe in my workspace.
dframe<-data.frame(person=c("Stan","Francine","Steve","Roger","Hayley","Klaus"),
                   sex=factor(c("M","F","M","M","F","M"),levels=c("F","M")),
                   funny=factor(c("High","Med","Low","High","Med","Med"),
                    levels=c("Low","Med","High")))
dframe
##     person sex funny
## 1     Stan   M  High
## 2 Francine   F   Med
## 3    Steve   M   Low
## 4    Roger   M  High
## 5   Hayley   F   Med
## 6    Klaus   M   Med
#(b)
dframe$age<-c(41,41,15,1600,21,60)
dframe
##     person sex funny  age
## 1     Stan   M  High   41
## 2 Francine   F   Med   41
## 3    Steve   M   Low   15
## 4    Roger   M  High 1600
## 5   Hayley   F   Med   21
## 6    Klaus   M   Med   60
#(c)
dframe<-data.frame(dframe$person,dframe$age,dframe$sex,dframe$funny)
dframe
##   dframe.person dframe.age dframe.sex dframe.funny
## 1          Stan         41          M         High
## 2      Francine         41          F          Med
## 3         Steve         15          M          Low
## 4         Roger       1600          M         High
## 5        Hayley         21          F          Med
## 6         Klaus         60          M          Med
names(dframe)<-c("person","age","sex","funny")
dframe
##     person  age sex funny
## 1     Stan   41   M  High
## 2 Francine   41   F   Med
## 3    Steve   15   M   Low
## 4    Roger 1600   M  High
## 5   Hayley   21   F   Med
## 6    Klaus   60   M   Med
#OR
dframe<-data.frame(dframe[,c(1,4,2,3)])
dframe
##     person funny  age sex
## 1     Stan  High   41   M
## 2 Francine   Med   41   F
## 3    Steve   Low   15   M
## 4    Roger  High 1600   M
## 5   Hayley   Med   21   F
## 6    Klaus   Med   60   M
#(d)
#Noting that mydata is saved already

mydata2<-mydata[,-5]
mydata2
##   person age sex funny
## 1  Peter  42   M  High
## 2   Lois  40   F  High
## 3    Meg  17   F   Low
## 4  Chris  14   M   Med
## 5 Stewie   1   M  High
## 6  Brain   7   M   Med
#(e)
mydataframe<-rbind(mydata2,dframe)
mydataframe
##      person  age sex funny
## 1     Peter   42   M  High
## 2      Lois   40   F  High
## 3       Meg   17   F   Low
## 4     Chris   14   M   Med
## 5    Stewie    1   M  High
## 6     Brain    7   M   Med
## 7      Stan   41   M  High
## 8  Francine   41   F   Med
## 9     Steve   15   M   Low
## 10    Roger 1600   M  High
## 11   Hayley   21   F   Med
## 12    Klaus   60   M   Med
#(f)
#mydataframe$person&mydataframe$age[(mydataframe$funny)=="Med"|(mydataframe$funny)=="High"]
#mydataframe

# f
subset(mydataframe, sex == "F" & (funny == "Med" | funny == "High"),
       select = c(person, age))
##      person age
## 2      Lois  40
## 8  Francine  41
## 11   Hayley  21
#(g)

subset(mydataframe, substr(person, 1, 1) == "S")
##   person age sex funny
## 5 Stewie   1   M  High
## 7   Stan  41   M  High
## 9  Steve  15   M   Low
#Note:
  #substr(x,start,stop)
#subset(x,subset,select)

#*Note that this are #bases*.

#list of important symbols #for extraction:

#[[ ]],
#[ ],
# $,
 #[ , ].

Tuesday 9th September 2025.

#Creating some objects to test out the special value "Inf".
foo<-Inf
foo
## [1] Inf
bar<-c(3401,Inf,3.1,-555,Inf,43)
bar
## [1] 3401.0    Inf    3.1 -555.0    Inf   43.0
baz<-90000^100
baz
## [1] Inf
#R can also represent negative infinite numbers.
qux<-c(-42,565,-Inf,-Inf,Inf,-45632.3)
qux
## [1]    -42.0    565.0     -Inf     -Inf      Inf -45632.3
#Multiplication with infinity
Inf*-9
## [1] -Inf
#it's result in a negative number because any negative value multiplied by infinity results to negative Inf'

#Other operations with the special value infinity.
Inf+1
## [1] Inf
4*-Inf
## [1] -Inf
-45.2-Inf
## [1] -Inf
Inf-45.2
## [1] Inf
Inf+Inf
## [1] Inf
Inf/23
## [1] Inf
#Zero and infinity goes hand in hand as thus:
-59/Inf
## [1] 0
-59/-Inf
## [1] 0
#Though this is not mathematically correct.Any nonzero value divide by infinity result in infinity.
-59/0
## [1] -Inf
59/0
## [1] Inf
Inf/0
## [1] Inf
#Detecting infinite and finite values in a data structure with "is.finite and is.infinite" functions!
qux
## [1]    -42.0    565.0     -Inf     -Inf      Inf -45632.3
is.infinite(qux)
## [1] FALSE FALSE  TRUE  TRUE  TRUE FALSE
is.finite(qux)
## [1]  TRUE  TRUE FALSE FALSE FALSE  TRUE
#Note that the function "is.finite" is the negation of "is.infinite".

#Relational operator on the special value Inf.
-Inf<Inf
## [1] TRUE
Inf>Inf
## [1] FALSE
qux==Inf
## [1] FALSE FALSE FALSE FALSE  TRUE FALSE
qux==-Inf
## [1] FALSE FALSE  TRUE  TRUE FALSE FALSE
# The special value NaN (Not a number)
foo<-NaN
foo
## [1] NaN
bar<-c(NaN,54.3,-2,NaN,90094.12,-Inf,55)
bar
## [1]      NaN    54.30    -2.00      NaN 90094.12     -Inf    55.00
#This example is strictly on when I don't want to see the value of the Inf!
-Inf+Inf
## [1] NaN
Inf/Inf
## [1] NaN
#NaN results when 0 divides 0.
0/0
## [1] NaN
#Note that any mathematical operation involving NaN results in NaN!
NaN+1
## [1] NaN
2+6*(4-4)/0
## [1] NaN
3.5^(-Inf/Inf)
## [1] NaN
#More
bar
## [1]      NaN    54.30    -2.00      NaN 90094.12     -Inf    55.00
is.nan(bar)
## [1]  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE
!is.nan(bar)
## [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
is.nan(bar)|is.infinite(bar)
## [1]  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE
a<-is.nan(bar)|is.infinite(bar)

#Extraction with "is.nan"
bar[-a]
## [1]    54.30    -2.00      NaN 90094.12     -Inf    55.00
bar[-(which(is.nan(bar)|is.infinite(bar)))]
## [1]    54.30    -2.00 90094.12    55.00

Wednesday 10th September 2025.

#Exercise 6.1
#Solution.
#(a)
foo<-c(13563,-14156,-14319,16981,12921,11979,9568,8833,-12968,8133)

#(i) #Outputting those values of foo that when raised to the power of 75 would be infinity.
foo[!is.finite(foo^(75))]
## [1]  13563 -14156 -14319  16981  12921 -12968
#(ii)
foo[-(foo^(75)==-Inf)]
## [1] -14156 -14319  16981  12921  11979   9568   8833 -12968   8133
#Returning the elements of foo that when raise to the power of 75 does not return negative Inf.

#(b)
bar<-matrix(c(77875.40,-35466.25,-39803.81,27551.45,-7333.85,55976.34,2376.30,36599.69,76694.82,-36478.88,-70585.69,47032.00),3,4)
bar
##           [,1]     [,2]     [,3]      [,4]
## [1,]  77875.40 27551.45  2376.30 -36478.88
## [2,] -35466.25 -7333.85 36599.69 -70585.69
## [3,] -39803.81 55976.34 76694.82  47032.00
#(i)
which(is.nan(bar^65/Inf))
## [1]  1  6  9 11
#Identifying the coordinate specific indexes of the entries in bar.

#(ii)
#Returning those values that are in bar that are not NaN.
which(!is.nan(bar^67+Inf))
##  [1]  1  2  3  4  5  6  7  8  9 10 12
A<-which(!is.nan(bar^67+Inf))

#Confirmation
A==which(bar^67!=-Inf)
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#(iii)
bar[(bar^67 == -Inf) | is.finite(bar^67)]
## [1] -35466.25 -39803.81  27551.45  -7333.85   2376.30  36599.69 -36478.88
## [8] -70585.69

Thursday 11th September 2025.

#Na
#Examples of NA values (Not available)
#For character vector type
foo<-c("character","a",NA,"with","string",NA)
foo
## [1] "character" "a"         NA          "with"      "string"    NA
#for factor vector data type
bar<-factor(c("blue",NA,NA,"blue","green",NA,"red","red",NA,"green"))
bar
##  [1] blue  <NA>  <NA>  blue  green <NA>  red   red   <NA>  green
## Levels: blue green red
#for numeric vector
baz<-matrix(c(1:3,NA,5,6,NA,8,NA),3,3)
baz
##      [,1] [,2] [,3]
## [1,]    1   NA   NA
## [2,]    2    5    8
## [3,]    3    6   NA
#Identifying and eliminating the Not available values in an object.
qux<-c(NA,5.89,Inf,NA,9.43,-2.35,NaN,2.10,-8.53,-7.58,NA,-4.58,2.01,NaN)
qux
##  [1]    NA  5.89   Inf    NA  9.43 -2.35   NaN  2.10 -8.53 -7.58    NA -4.58
## [13]  2.01   NaN
#Checking foe NA
is.na(qux)
##  [1]  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
## [13] FALSE  TRUE
#Separating between the NA and NaN when extracted this values in the same vector environs.
which(is.nan(qux))  #This is to only identify NaN values.
## [1]  7 14
#Identifying only the NA values!
which(is.na(qux)&!is.nan(qux))
## [1]  1  4 11
#Deleting all NAs values in a vector with "na.omit"
quux<-na.omit(qux)
quux
## [1]  5.89   Inf  9.43 -2.35  2.10 -8.53 -7.58 -4.58  2.01
## attr(,"na.action")
## [1]  1  4  7 11 14
## attr(,"class")
## [1] "omit"
#Performing arithmetic operation with NA and NaN.
3+2.1*NA-4
## [1] NA
3*c(1,2,NA,NA,NaN,6)
## [1]   3   6  NA  NA NaN  18
76>NaN
## [1] NA
#NULL value
foo<-NULL
foo
## NULL
bar<-NA
bar
## [1] NA
#Vectorized NULL, noting that NULL is a value that represents an empty element.
c(2,4,NA,8)
## [1]  2  4 NA  8
c(2,4,NULL,8)
## [1] 2 4 8
#Null Another explicit example
c(NA,NA,NA)  #Unrecorded observation
## [1] NA NA NA
c(NULL,NULL,NULL)  #Emptiness three times
## NULL
#Using the is.null function to extract the facts that the vector is actually NULL or not.
opt.arg<-c("string1","string2","string3")

#Checking whether the argument supplied using NA
is.na(opt.arg)
## [1] FALSE FALSE FALSE
#'is.na' operates element wise and that means there would be values present in the output that might be problematic.
is.null(opt.arg)
## [1] FALSE
#Checking again for na,and null flags
opt.arg<-c(NA,NA,NA)
is.na(opt.arg)
## [1] TRUE TRUE TRUE
opt.arg<-c(NULL,NULL,NULL)
is.null(opt.arg)
## [1] TRUE
#Some little operation with NULL
NULL+53
## numeric(0)
53<=NULL
## logical(0)
#With some special symbols
NaN-NULL+NA/Inf
## numeric(0)
#Examining List and dataframe
foo<-list(member1=c(33,1,5.2,7),member2="NA or NULL?")
foo
## $member1
## [1] 33.0  1.0  5.2  7.0
## 
## $member2
## [1] "NA or NULL?"
#Accessing a member in foo
foo$member3  #Result into NULL
## NULL
#Filling an empty member with a value
foo$member3<-NA
foo
## $member1
## [1] 33.0  1.0  5.2  7.0
## 
## $member2
## [1] "NA or NULL?"
## 
## $member3
## [1] NA

Friday 12th September 2025.

#Exercise 6.2
#(a)
foo<-c(4.3,2.2,NULL,2.4,NaN,3.3,3.1,NULL,3.4,NA)
foo
## [1] 4.3 2.2 2.4 NaN 3.3 3.1 3.4  NA
#(i)
length(foo)
## [1] 8
#(ii)
which(is.na(foo))
## [1] 4 8
#(iii)
is.null(foo)
## [1] FALSE
#(iv)
is.na(foo[8])+4/NULL
## numeric(0)
#(b)
A<-list(c(7,7,NA,3,NA,1,1,5,NA))

#(i)
names(A)<-"alpha"

#(ii)
A$beta
## NULL
#(iii)
A$beta<-which(is.na(A$alpha))
A
## $alpha
## [1]  7  7 NA  3 NA  1  1  5 NA
## 
## $beta
## [1] 3 5 9
#ggplot2 class
library(ggplot2)

#Using ggplot2 package

foo<-c(1.1,2,3.5,3.9,4.2)
bar<-c(2,2.2,-1.3,0,0.2)

qplot(foo,bar)
## Warning: `qplot()` was deprecated in ggplot2 3.4.0.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

qplot(foo,bar,main="My Lovely qplot",xlab = "X axis Label",ylab="Location y")

qplot(foo,bar,main="My Lovely qplot",xlab = "X axis Label",ylab="Location y")+
  geom_line(type="n",lty=7,col="red",lwd=2)
## Warning in geom_line(type = "n", lty = 7, col = "red", lwd = 2): Ignoring
## unknown parameters: `type`

Week 8

Monday 15th September 2025.

6.2 Understanding Types, Classes, and Coercion

Atributes
Consider the following example with an attribute function :
   foo<-matrix(data=1:9,nrow=3,ncol=3)
foo   
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
Now applying the attribute function
attributes(foo)
## $dim
## [1] 3 3
Calling or to find the attribute the content of dim.
attributes(foo)$dim
## [1] 3 3
For the dimension of a matrix we’ve already that dim(x) produces the dimensions of vector matrix “X”
dim(foo)
## [1] 3 3

Tuesday 16th September 2025.

Creating a matrix and attributing names to the row and column of the matrix using the “dimnames” function.
bar<-matrix(1:9,3,3,dimnames = list(c("A","B","C"),c("D","E","F")))
bar
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9
Note that if you didn’t attribute “dimnames” to the matrix as an optional function if you call it, it’ll only return NULL result.
attributes(bar)
## $dim
## [1] 3 3
## 
## $dimnames
## $dimnames[[1]]
## [1] "A" "B" "C"
## 
## $dimnames[[2]]
## [1] "D" "E" "F"
Modifying some attributes using attribute-specific function.
dimnames(foo)<-list(c("A","B","C"),c("D","E","F"))
foo
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9
Stand-alone Vectors: Note that stand alone vectors does not have anything to do with attributes.

E.g

num.vec1<-1:4
num.vec1
## [1] 1 2 3 4
num.vec2<-seq(1,4,len=6)
num.vec2
## [1] 1.0 1.6 2.2 2.8 3.4 4.0
char.vec<-c("a","few","strings","here")
char.vec
## [1] "a"       "few"     "strings" "here"
logic.vec<-c(T,F,F,F,T,F,T,T)
logic.vec
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8  3
## [26] -1  1 -3  1  5  3  4  8  3  4  8
fac.vec<-factor(c("Blue","Blue","Green","Red","Green","Yellow"))
fac.vec
## [1] Blue   Blue   Green  Red    Green  Yellow
## Levels: Blue Green Red Yellow
Checking the classes of Objects stored in R with the “class” function.
class(num.vec1)
## [1] "integer"
class(num.vec2)
## [1] "numeric"
class(char.vec)
## [1] "character"
class(logic.vec)
## [1] "numeric"
class(fac.vec)
## [1] "factor"
class(foo)
## [1] "matrix" "array"
class(bar)
## [1] "matrix" "array"
Checking for the structure of the date stored in and object in R with the function “class”.
num.mat1<-matrix(num.vec1,2,2)
num.mat1
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
num.mat2<-matrix(num.vec2,2,3)
num.mat2
##      [,1] [,2] [,3]
## [1,]  1.0  2.2  3.4
## [2,]  1.6  2.8  4.0
char.mat<-matrix(char.vec,2,2)
char.mat
##      [,1]  [,2]     
## [1,] "a"   "strings"
## [2,] "few" "here"
logic.mat<-matrix(logic.vec,4,2)
## Warning in matrix(logic.vec, 4, 2): data length differs from size of matrix:
## [36 != 4 x 2]
logic.mat
##      [,1] [,2]
## [1,]    3   -1
## [2,]    4    1
## [3,]    8   -3
## [4,]    3    1
fac.mat<-matrix(fac.vec,2,3) #Note that factors are only used in vector form.
fac.mat
##      [,1]   [,2]    [,3]    
## [1,] "Blue" "Green" "Green" 
## [2,] "Blue" "Red"   "Yellow"
Check the matrix with “class” function.
class(num.mat1)
## [1] "matrix" "array"
class(num.mat2)
## [1] "matrix" "array"
class(char.mat)
## [1] "matrix" "array"
class(logic.mat)
## [1] "matrix" "array"
class(fac.mat) #Not associated with c;lass!
## [1] "matrix" "array"
Multiple Classes
ordfac.vec<-factor(c("Small","Large","Large","Regular","Small"),
                   levels=c("Small","Regular","Large"),
                   ordered=TRUE)
ordfac.vec
## [1] Small   Large   Large   Regular Small  
## Levels: Small < Regular < Large
Checking the class:
class(ordfac.vec)
## [1] "ordered" "factor"
is-Dot function can check for any class name!
num.vec1<-1:4
num.vec1
## [1] 1 2 3 4
is.integer(num.vec1)
## [1] TRUE
is.numeric((num.vec1))
## [1] TRUE
is.matrix(num.vec1)
## [1] FALSE
is.data.frame(num.vec1)
## [1] FALSE
is.vector(num.vec1)
## [1] TRUE
is.logical(num.vec1)
## [1] FALSE
As-Dot Coercion functions:Implicit Coercion, converting

logical values to thier numeric counterparts.

1:4+c(T,F,F,T)
## Warning in 1:4 + c(T, F, F, T): longer object length is not a multiple of
## shorter object length
##  [1]  4  6 11  7  0  3  0  5  6  5  2  5 -2  3  8  7  5 10
Note this the results are given in the context of numerical values given that F=0 and T=1
Using the Cat and Paste function to glue and coerce some values.
foo<-34
bar<-T

paste("Definitely foo: ",foo,"; definitely bar: ",bar,".",sep="")
## [1] "Definitely foo: 34; definitely bar: 3."
## [2] "Definitely foo: 34; definitely bar: 4."
## [3] "Definitely foo: 34; definitely bar: 8."
Other example of coercion
as.numeric(c(T,F,F,T))
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
1:4+as.numeric(c(T,F,F,T))
## Warning in 1:4 + as.numeric(c(T, F, F, T)): longer object length is not a
## multiple of shorter object length
##  [1]  4  6 11  7  0  3  0  5  6  5  2  5 -2  3  8  7  5 10
foo<-34
foo.ch<-as.character(foo)
foo.ch
## [1] "34"
bar<-T
bar.ch<-as.character(bar)
bar.ch
## [1] "3" "4" "8"
paste("Definitely foo: ",foo.ch,"; definitely bar: ",bar.ch,".",sep="")
## [1] "Definitely foo: 34; definitely bar: 3."
## [2] "Definitely foo: 34; definitely bar: 4."
## [3] "Definitely foo: 34; definitely bar: 8."
Coercion makes sense when there is possibilities.
as.numeric("32.4")
## [1] 32.4
Coercion that does not make sense
as.numeric("g'day mate")
## Warning: NAs introduced by coercion
## [1] NA
Example of Coercion of some values to another. However in some cases direct coercion cannot work but multiple coercion does work.
as.logical(c("1","0","1","0","0"))
## [1] NA NA NA NA NA
However this does work.
as.logical(as.numeric(c("1","0","1","0","0")))
## [1]  TRUE FALSE  TRUE FALSE FALSE
Another way of coercion.
as.numeric(as.logical(as.numeric(c("1","0","1","0","0"))))
## [1] 1 0 1 0 0
Converting or coercing a factor data into a numeric data.
baz<-factor(c("male","male","female","male"))
baz
## [1] male   male   female male  
## Levels: female male
Conversion
as.numeric(baz)
## [1] 2 2 1 2
Note for this : Because it is very important.
qux<-factor(c(2,2,3,5))
qux
## [1] 2 2 3 5
## Levels: 2 3 5
as.numeric(qux)
## [1] 1 1 2 3
2*as.numeric(qux)
## [1] 2 2 4 6
Coercion between object classes
foo<-matrix(1:4,2,2)
foo
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
Now checking
as.vector(foo) #Coercing to a vector
## [1] 1 2 3 4
Coercion of higher dimensional arrays,in order of layer or block.
bar<-array(c(8,1,9,5,5,1,3,4,3,9,8,8),dim=c(2,3,2))
bar
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]    8    9    5
## [2,]    1    5    1
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]    3    3    8
## [2,]    4    9    8
Coercing array to other data structure.
as.matrix(bar)
##       [,1]
##  [1,]    8
##  [2,]    1
##  [3,]    9
##  [4,]    5
##  [5,]    5
##  [6,]    1
##  [7,]    3
##  [8,]    4
##  [9,]    3
## [10,]    9
## [11,]    8
## [12,]    8
as.vector(bar)
##  [1] 8 1 9 5 5 1 3 4 3 9 8 8
Coercion for data type.
baz<-list(var1=foo,var2=c(T,F,T),var3=factor(c(2,3,4,4,2)))
baz
## $var1
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $var2
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8
## 
## $var3
## [1] 2 3 4 4 2
## Levels: 2 3 4
Now converting to other data structure
#as.data.frame(baz) #Error occur because they are of no similar length.
Now in the new
qux<-list(var1=c(3,4,5,1),var2=c(T,F,T,T),var3=factor(c(4,4,2,1)))
qux
## $var1
## [1] 3 4 5 1
## 
## $var2
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $var3
## [1] 4 4 2 1
## Levels: 1 2 4
Now coercing the data structure.
#as.data.frame(qux)
#qux
Exercise 6.3

Solution (a)

foo<-array(1:36,dim=c(3,3,4))
bar<-as.vector(foo)
baz<-as.character(bar)
qux<-as.factor(baz)
quux<-bar+c(-0.1,0.1)
Checking the classes using the “class function”
class(foo) #Explicit
## [1] "array"
class(bar) #Explicit
## [1] "integer"
class(baz) #Implicit
## [1] "character"
class(qux) #Implicit
## [1] "factor"
class(quux) #Explicit
## [1] "numeric"
a<-is.numeric(foo)+is.integer((foo))
b<-is.numeric(bar)+is.integer(bar)
c<-is.numeric(baz)+is.integer(baz)
d<-is.numeric(qux)+is.integer(qux)
e<-is.numeric(quux)+is.integer(quux)

Result_fac<-factor(c(a,b,c,d,e))
Result_fac
## [1] 2 2 0 0 1
## Levels: 0 1 2
as.numeric(Result_fac)
## [1] 3 3 1 1 2
(Result_fac)==as.numeric(Result_fac)
## [1] FALSE FALSE FALSE FALSE FALSE
vec_mat<-matrix(c(2,3,4,5,6,7,8,9,10,11,12,13),3,4)
vec_mat
##      [,1] [,2] [,3] [,4]
## [1,]    2    5    8   11
## [2,]    3    6    9   12
## [3,]    4    7   10   13
as.character(vec_mat)
##  [1] "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13"

(d)i.

vec_mat2<-matrix(c(34,23,33,42,41,0,1,1,0,0,1,2,1,1,2),5,3)
vec_mat2
##      [,1] [,2] [,3]
## [1,]   34    0    1
## [2,]   23    1    2
## [3,]   33    1    1
## [4,]   42    0    1
## [5,]   41    0    2

Coercing to data.frame

A<-as.data.frame(vec_mat2)
A
##   V1 V2 V3
## 1 34  0  1
## 2 23  1  2
## 3 33  1  1
## 4 42  0  1
## 5 41  0  2

Coercing the second column to be logical values.

A$V2<-as.logical((A$V2))
A
##   V1    V2 V3
## 1 34 FALSE  1
## 2 23  TRUE  2
## 3 33  TRUE  1
## 4 42 FALSE  1
## 5 41 FALSE  2

Chapter 7

Basic Plotting

foo<-c(1.1,2,3.5,3.9,4.2)
bar<-c(2,2.2,-1.3,0,0.2)
Applying the plot basic function using R’s default behavior
plot(foo,bar)

Trying another format (i.e I can combine the two input of all the axis in touch)
baz<-cbind(foo,bar)
baz
##      foo  bar
## [1,] 1.1  2.0
## [2,] 2.0  2.2
## [3,] 3.5 -1.3
## [4,] 3.9  0.0
## [5,] 4.2  0.2
plot(baz,main="My Plot")

Wednesday 17th September 2025.

Graphical Parameters.

With the following parameters one can decorate or make beautiful a plot at their expense. These parameters include: type tells R how to plot: Either scatter without their point joined or joining the points. main,xlab,ylab Options to include the plot tiltle: The “main” handles the main title of the plot while “xlab and ylab” handles the “X and Y-axis” Labels. col Color: Used for plotting points or lines. pch Stands for point character. This selects which character to use for individual plotting points. cex Stands for character expansion. Controls the size of plotted point character. lty Stands for line type. This specifies the type of line to be used in connecting the points plotted. lwd Stands for line width. This controls the thickness of plotted lines. xlim,ylim This provides limits for the horizontal range and vertical range of the plotting region.

7.2.1 Automatic Plot Types

Adding plot type (this can also occur when plotting time series).

#plot(foo,bar,type="l")  # type="l" means line only.
#plot(foo,bar,type="b") # type="b" both lines and points.
#plot(foo,bar,type="o") # type="o" means overplotting the points with line.
plot(foo,bar,type="n") # type="n" No point or line. And it is very important for complicated plots that must be constructed in steps.

7.2.2 Title and Axis Labels

Making a Plot easier to interpret.

#plot(foo,bar,type="b",main="My Lovely Plot",xlab = "x axis label",ylab = "location y")

plot(foo,bar,main="My Lovely Plot\ntitle on two lines",type="b",xlab="",ylab="")

Notice that the Main Title is written in two lines: That’s because we place a line brake operator ()

7.2.3 Color

Adding color to a graph is far from just an aesthetic consideration. Color can make data much clearer-for example by distinguishing factor levels or emphasizing important numeric limits.

Example of Clored graphs.
#plot(foo,bar,type="b",main="My Lovely plot",xlab = "",ylab="",col=2)

plot(foo,bar,type="b",main="My Lovely plot",xlab = "",ylab="",col="seagreen4")

Plot on second spot.
plot(foo,bar,type="b",xlab="",ylab="",col="blue",pch=8,lty=5,cex=1,lwd=5,xlim=c(-10,5),ylim = c(-3,3))

Third Plot
plot(foo,bar,type="b",main="My lovely Plot",xlab="",ylab="",col=2,pch=1,cex=0.8,lty=2,lwd=2,xlim=c(3,5),ylim=c(-0.5,0.2))

Fourth Plot
plot(foo,bar,type="b",main="My lovely Plot",xlab="",ylab="",col="blue",pch=8,cex=2,lwd=2,lty=2)

Thursday 18th September 2025

Line and Point Appearance

Usig pch,lty and cex to make choice of point character and the tpype of line to be used!

plot(foo,bar,type="p",main="My lovely Plot",xlab="",ylab="",col=1:7,pch=1:25,lty=2,cex=2.3,lwd=3.3)

Trying something

plot(c(1:8),c(1:8),type="p",main = "col=",xlab="",ylab="",pch=21,bg=c("black", "red", "green", "blue", "skyblue","maroon2","yellow","grey"),col="black")

From chat Gpt

pch_values <- 21
colors <- c("red", "blue", "green", "purple", "gray")

plot(1:5, 1:5, type="b",
     pch = pch_values, 
     col = "black", 
     bg = colors, 
     cex = 3, lwd = 2)

Plot for pch

plot(seq(5,25),seq(5,25),type="b",xlab="",ylab="",main="pch=",pch=1:25,cex=2.3)

plot for lty

plot(foo,bar,type="b",main="My lovely plot",xlab = "",ylab="",col=4,pch=8,lty=2,cex=2.3,lwd=3.3)

Second plot on top.

plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="",col=6,pch=15,lty=3,cex=0.7,lwd=2)

Friday 19th September 2025.

Welcome to Plotting Region Limits.

there are basic arguments for the limit functions given a plot: xlim and ylim. We supply numeric parameters into this function as thus: c(lower,upper).

Consider the following examples:

plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="",col=4,pch=8,lty=2,cex=2.3,lwd=3.3,xlim=c(-10,5),ylim=c(-3,3))

Second example

plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="",col=6,pch=15,lty=3,cex=0.7,lwd=,xlim=c(3,5),ylim=c(-0.5,0.2))

The beauty of plotting is in knowing the arguments for every aesthetic needed to beatify the plotting outcome.

7.3 Adding Points, Lines, and Text to an Existing Plot.

Ready to use funcytion in R that adds to a plot without refreshing or clearing the windows:

Note the word: “Canvas”! points Adds points lines,abline,segments Adds lines text Writes text arrows Adds arrows legend Adds a legend

The syntax for calling and setting parameters for these functions is the same as plot.

Example on this platform.

Loading a set of 20 data: on x and y object vector.

Plotting an ellaborate final plot of some hypothetical data.

Ten lines of Code were used to build this plot in it’s entirety (plus one additional line to add the legend). The plot as it looks at each step, is given.

Step by step methodical codes for a desired output:

x<-1:20
y<-c(-1.49,3.37,2.59,-2.78,-3.94,-0.92,6.43,8.51,3.41,-8.23,-12.01,-6.58,2.87,14.12,9.63,-4.58,-14.78,-11.67,1.17,15.62)
#1.Creating a empty plot

plot(x,y,type="n",main="")


#2. The "abline" function and it's #use.
#Note: The "abline" function adds #straight lines spanning a plot, as #thus;


abline(h=c(-5,5),col="red",lty=2,lwd=2)


#3. Adding shorter lines with #"segments".


segments(x0=c(5,15),y0=c(-5,-5),x1=c(5,15),y1=c(5,5),col="red",lty=3,lwd=2)


#4. Adding specific coordinates from #x and y values with the function #"point" to beautify the plot with #needed aes functions.


points(x[y>=5],y[y>=5],pch=4,col="darkmagenta",cex=2)


#5.The same code as that of 4, but #this time we extracts the values of #y, less or equal to -5, and assign #+ to the points and set their #colors to dark green.


points(x[y<=-5],y[y<=-5],pch=3,col="darkgreen",cex=2)


#6. Adding blue "sweet spot" points #slightly complicated.


points(x[(x>=5&y<=15)&(y>-5&y<5)],y[(x>=5&y<=15)&(y>-5&y<5)],pch=19,col="blue")


#7.Plotting No graphical parameters #with default black.


points(x[(x<5|x>15)&(y>-5&y<5)],y[(x<5|x>15)&(y>-5&y<5)])


# To draw lines connecting the #coordinates  in x and y  with #"lines".


lines(x,y,lty=4)


#9. Adding arrows pointing the sweet #point with "arrows".


arrows(x0=8,y0=14,x1=11,y1=2.5)


#10.  Adding Lael to the Plot #outcome with "text"


text(x=8,y=15,label="sweet")

#11.Adding Legend with the "legend" #function.

legend("bottomleft",
legend=c("overall process","sweet","standard","too big","too small","sweet y range","sweet x range"),
pch=c(NA,19,1,4,3,NA,NA),lty=c(4,NA,NA,NA,NA,2,3),col=c("black","darkmagenta","darkgreen","red","red"),lwd=c(1,NA,NA,NA,NA,2,2),pt.cex=c(NA,1,1,2,2,NA,NA),cex=0.5)

Note: The first argument sets where the legend should be placed.

Exercise 7.1 solution to (a)

x<--3:3
y<-7:13

plot(x,y,type="n",main="" )
abline(h=c(7,13),col="grey",lty=2,lwd=2,cex=2)
abline(v=c(-3,3),col="grey",lty=2,lwd=2,cex=2)
arrows(x0=-2.5,y0=7.5,x1=-1,y1=9.5,angle =15)
arrows(x0=-2.5,y0=10,x1=-1,y1=10)
arrows(x0=-2.5,y0=12.5,x1=-1,y1=10.5)
arrows(x0=2.5,y0=7.5,x1=1,y1=9.5)
arrows(x0=2.5,y0=10,x1=1,y1=10)
arrows(x0=2.5,y0=12.5,x1=1,y1=10.5)
text(x=0,y=10,labels="SOMETHING\n PROFOUND"
     ,cex=1)

Week 9

Monday 22nd September 2025.

Exercise 7.1 Continues (b) The plot

# Build data frame
Bag <- data.frame(
  Weight = c(55,85,75,42,93,63,58,75,89,67),
  Height = c(161,185,174,154,188,178,170,167,181,178),
  Sex = factor(c("female","male","male","female",
                 "male","male","female","male","male","female"))
)

# Define mappings explicitly by factor levels
col_map <- c(female = "red", male = "blue")
pch_map <- c(female = 17,    male = 16)

# Scatter plot
plot(
  Bag$Weight, Bag$Height,
  col = col_map[Bag$Sex],
  pch = pch_map[Bag$Sex],
  xlab = "Weight (kg)",
  ylab = "Height (cm)",
  main = "Scatterplot of Weight vs Height by Sex"
)

# Legend
legend(
  "topleft",
  legend = names(col_map),
  col = col_map,
  pch = pch_map,
  title = "Sex",
  cex = 0.8
)

Tuesday 23rd September 2025.

7.4 The ggplot2 Package.

Apart from the R’s built in graphical tools (often called base R graphics or traditional R graphics), we have a more advanced and human base suite of graphical tools: ggplot 2, a prominent contributed package which offers particular powerful alternatives to the standard plotting procedures in R. The gg stands for grammer of graphics.

7.4.1 A quik plot with “qplot”

Underlying Procedure for ggplot2: Installation and loading the “ggplot2” package

#install.packages("ggplot2")
library("ggplot2")

An Example using the “qplot” known as (quick plot) function.

foo<-c(1.1,2,3.5,3.9,4.2)
bar<-c(2,2.2,-1.3,0,0.2)

#Producing a qplot version of the plot in 7.1.
qplot(foo,bar,type="p",main="My lovely Plot",xlab="x axis label",ylab="location y")
## Warning in geom_point(type = "p"): Ignoring unknown parameters: `type`

#See the clear difference between qplot and traditional R graphics.

baz<-plot(foo,bar)

baz  # Displays NULL
## NULL
#But now check this out...
qux<-qplot(foo,bar)
qux #Behaves like an object vector.

7.4.2 Setting Apperance Constants with Geoms

To add and customize points and lines in a ggplot2 graphic, rather than using a long list of arguments or secondary functions executed separately (such as points or lines). You can modify the object using ggplot2’s convenient suite of geometric modifiers , known as geoms.

Example: Adding geoms to the qplot object using the + operator.

qplot(foo,bar,geom="blank")+geom_point()+geom_line()

Without adding arguments in the geom function it automatically uses the defualt R setting.

Now specifying some literal arguments:

qplot(foo,bar,geom = "blank")+geom_point(size=3,shape=6,color="blue")+geom_line(color="red",linetype=2,linewidth=0.6)

Point character (pch) is to “shape” and character expansion (cex) is to “size” in ggplot2.

Example: Applying those arguments in the geom function with the object oriented nature of ggplot2, we can simply do these;

myqplot<-qplot(foo,bar,geom="blank")+geom_line(color="red",linetype=2)
myqplot+geom_point(size=3,shape=3,color="blue")

myqplot+geom_point(size=3,shape=7,color="blue")

There are a number of geometric modifiers that can be called using a function name beginning with geom_ in ggplot2.

x<-1:20
y<-c(-1.49,3.37,2.59,-2.78,-3.94,-0.92,6.43,8.51,3.41,-8.23,-12.01,-6.58,2.87,14.12,9.63,-4.58,-14.78,-11.67,1.17,15.62)

ptype<-rep(NA,length(x))
ptype[y>=5]<-"too_big"
ptype[y<=-5]<-"too_small"
ptype[(x>=5&x<=15)&(y>-5&y<5)]<-"sweet"
ptype[(x<5|x>15)&(y>-5&y<5)]<-"standard"
ptype<-factor(ptype)
ptype
##  [1] standard  standard  standard  standard  sweet     sweet     too_big  
##  [8] too_big   sweet     too_small too_small too_small sweet     too_big  
## [15] too_big   standard  too_small too_small standard  too_big  
## Levels: standard sweet too_big too_small
#Now you have  a factor with woo values sorted into four levels

qplot(x,y,color=ptype,shape=ptype)+
# Initial call to qplot which maps point cahracter tor points.
geom_point(size=4)+geom_line(mapping = aes(group=1),
  color="black",lty=2)+
  geom_hline(mapping=aes(yintercept = c(-5,5)),color="red")+
  geom_segment(mapping = aes(x=5,y=-5,xend = 5,yend=5),color="red",lty=3)+
  geom_segment(mapping=aes(x=15,y=-5,xend=15,yend=5),color="red",lty=3)

Exercise 7.2 Solution:

Bag<-data.frame('Weight(kg)'=c(55,85,75,42,93,63,58,75,89,67),'Height(cm)'=c(161,185,174,154,188,178,170,167,181,178),Sex=factor(c("female","male","male","female","male","male","female","male","male","female")))
Bag
##    Weight.kg. Height.cm.    Sex
## 1          55        161 female
## 2          85        185   male
## 3          75        174   male
## 4          42        154 female
## 5          93        188   male
## 6          63        178   male
## 7          58        170 female
## 8          75        167   male
## 9          89        181   male
## 10         67        178 female
# Rename columns once for simplicity
names(Bag) <- c("Weight", "Height", "Sex")

# Plot with ggplot2
ggplot(Bag, aes(x = Weight, y = Height, color = Sex, shape = Sex)) +
  geom_point(size = 3) +
  labs(
    title = "Scatterplot of Weight vs Height by Sex",
    x = "Weight (kg)",
    y = "Height (cm)"
  ) +
  theme_minimal()

Wednesday 24th September 2025.

Reading and Writing Files.

R-Ready Data Sets. To bring up a window lsting R’s ready to use data sets, we shall apply “data()”

data()

The exact list that appears depends on what contributed packages have been installed from CRAN.

8.1.1 Built-in Data Sets

To see a summary of the data sets contained in the package, you can use the “library” function as follows:

library(help="datasets")

Look at te first 15 records of Chickweight : Row is to records and column is to variables.

ChickWeight[1:15,]
##    weight Time Chick Diet
## 1      42    0     1    1
## 2      51    2     1    1
## 3      59    4     1    1
## 4      64    6     1    1
## 5      76    8     1    1
## 6      93   10     1    1
## 7     106   12     1    1
## 8     125   14     1    1
## 9     149   16     1    1
## 10    171   18     1    1
## 11    199   20     1    1
## 12    205   21     1    1
## 13     40    0     2    1
## 14     49    2     2    1
## 15     58    4     2    1
Contributed Data Sets
#install.packages("tseries"
library(tseries)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(help="tseries")

#To access the dataset "ice.river" we shall perform the following:
data("ice.river")
ice.river[1:15,]
##       flow.vat flow.jok prec temp
##  [1,]    16.10     30.2  8.1  0.9
##  [2,]    19.20     29.0  4.4  1.6
##  [3,]    14.50     28.4  7.0  0.1
##  [4,]    11.00     27.8  0.0  0.6
##  [5,]    13.60     27.8  0.0  2.0
##  [6,]    12.50     27.8  0.0  0.8
##  [7,]    10.50     27.8  1.9  1.4
##  [8,]    10.10     27.8  1.2  1.3
##  [9,]     9.68     27.8  0.0  2.2
## [10,]     9.02     27.3  0.1  0.1
## [11,]     8.80     27.3  0.0  3.0
## [12,]     8.58     27.3  0.2 -0.2
## [13,]     8.14     26.2  1.8 -2.6
## [14,]     7.50     25.2  0.2 -3.8
## [15,]     7.92     26.7  0.2  0.9
#This R-ready datasets helps us to test run our codes before we introduce any external dataset

Friday 26th September 2025.

8.2 Reading in External Data Files

Learning how to read table-format files. Easiest among the read and and import.

Header If a header is present,it’s always the first line of the file. The Delimiter the all-important delimiter is a character used to separate the entries in each line. Missing value This is another unique character string used exclusively to denote a missing value.

These files have a .txt extension (highlighting the plain-text style) or .csv (for comma-separated values).

Let’s try some examples:

mydatafile<-read.table(file="C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/8.2.1_mydatafile.txt",header=TRUE,sep=" ",na.strings = "*",stringsAsFactors=FALSE)

mydatafile
##   person age sex funny age.mon
## 1  Peter  NA   M  High     504
## 2   Lois  40   F  <NA>     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      NA
## 6  Brian  NA   M   Med      NA

Monday 29th September 2025.

I focused on Research.

Tuesday 30th September 2025.

Viewing textual output of the contents of any folder using “list.files”

list.files("C:/Users/hp")
##  [1] "Alushi"                                                                                      
##  [2] "Am.aux"                                                                                      
##  [3] "Am.log"                                                                                      
##  [4] "Am.nav"                                                                                      
##  [5] "Am.out"                                                                                      
##  [6] "Am.pdf"                                                                                      
##  [7] "Am.snm"                                                                                      
##  [8] "Am.synctex.gz"                                                                               
##  [9] "Am.tex"                                                                                      
## [10] "Am.toc"                                                                                      
## [11] "AppData"                                                                                     
## [12] "Application Data"                                                                            
## [13] "Contacts"                                                                                    
## [14] "Cookies"                                                                                     
## [15] "Documents"                                                                                   
## [16] "Downloads"                                                                                   
## [17] "Favorites"                                                                                   
## [18] "from itertools import combinations.py"                                                       
## [19] "IntelGraphicsProfiles"                                                                       
## [20] "Links"                                                                                       
## [21] "Local Settings"                                                                              
## [22] "Music"                                                                                       
## [23] "My Documents"                                                                                
## [24] "NetHood"                                                                                     
## [25] "NTUSER.DAT"                                                                                  
## [26] "ntuser.dat.LOG1"                                                                             
## [27] "ntuser.dat.LOG2"                                                                             
## [28] "NTUSER.DAT{84e988a2-cc3e-11ee-9edd-f430b9d08461}.TM.blf"                                     
## [29] "NTUSER.DAT{84e988a2-cc3e-11ee-9edd-f430b9d08461}.TMContainer00000000000000000001.regtrans-ms"
## [30] "NTUSER.DAT{84e988a2-cc3e-11ee-9edd-f430b9d08461}.TMContainer00000000000000000002.regtrans-ms"
## [31] "ntuser.ini"                                                                                  
## [32] "numpy"                                                                                       
## [33] "OneDrive"                                                                                    
## [34] "plot_expo.py"                                                                                
## [35] "PrintHood"                                                                                   
## [36] "python -m venv .venv"                                                                        
## [37] "Recent"                                                                                      
## [38] "Research.py"                                                                                 
## [39] "SA.tex"                                                                                      
## [40] "Sabina.tex"                                                                                  
## [41] "Saved Games"                                                                                 
## [42] "Searches"                                                                                    
## [43] "SendTo"                                                                                      
## [44] "Start Menu"                                                                                  
## [45] "Templates"                                                                                   
## [46] "TeXworks"                                                                                    
## [47] "untitled-1.tex"                                                                              
## [48] "Videos"                                                                                      
## [49] "Waf.tex"                                                                                     
## [50] "WPS Cloud Files"                                                                             
## [51] "Zotero"

Setting my working Directory:

getwd()
## [1] "C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8"
setwd("C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8")

#file.choose()

Using the same command “read.table” to again read mydatafile.txt.

#mydatafile<-read.table(file=file.choose("mydatafile"),header=TRUE,sep=" ",na.strings="*",stringsAsFactors=FALSE)
  
  save.image()

Thursday 2nd October 2025.

When importing data into data frames, keep in mind the difference between character string observations and factor observations. No factor attribute information is stored in the plain-text file, but read.table will convert non-numeric values into factors by default. Here, you want to keep some of your data saved as strings, so set stringsAsFactors=FALSE, which prevents R from treating all non numeric elements as factors.This way, person, sex, and funny are all stored as character strings.

Overwriting sex and funny with factor versions of themselves .

mydatafile$sex<-as.factor(mydatafile$sex)
mydatafile$funny<-factor(x=mydatafile$funny,levels=c("Low","Med","High"))

mydatafile
##   person age sex funny age.mon
## 1  Peter  NA   M  High     504
## 2   Lois  40   F  <NA>     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      NA
## 6  Brian  NA   M   Med      NA

8.2.2 Spreadsheet Workbooks

With “read.csv” importing spreedsheet file to the R environment with the “Comma Separated Values”.

spread<-read.csv(file="C:/Users/hp/Downloads/spreadsheetfile2.csv",header=FALSE,stringsAsFactors=TRUE)
spread
##    V1  V2     V3
## 1  55 161 female
## 2  88 185   male
## 3  75 174   male
## 4  42 154 female
## 5  93 188   male
## 6  63 178   male
## 7  58 170 female
## 8  75 167   male
## 9  89 181   male
## 10 67 178 female

Web-Based Files

With an Internet connection, R can read in files from a website with the same read.table command. All I need to do is to copy the Url and paste it in “read.table” command.

Example:

#dia.url<-"http://www.amstat.org/publications/jse/v9n2/4cdata.txt"
#diamonds<-read.table(dia.url)

#dia.url <- "https://jse.amstat.org/v9n2/4Cdata.txt"
#diamonds <- read.table(dia.url)
#diamonds


#Adding names to my just added online read in file.
#names(diamonds)<-c("Carat","Color","Clarity","Cert","Price")
#diamonds

#Now to read the first five records:
#diamonds[1:5,]

8.2.4 Other File Formats

There are other file formats besides .txt or .csv files that can be read into R, such as the data file format .dat. These files can also be imported using read.table, though they may contain extra information at the top that must be skipped using the optional skip argument.Other contributed packages on CRAN can help R handle files from various database management systems (DBMSs). For example, the RODBC package (Ripley and Lapsley, 2013) lets you query Microsoft Access databases and return the results as a data frame object. Other interfaces include the packages RMySQL (James and DebRoy, 2012) and RJDBC (Urbanek, 2013)

8.3 Writing out Data Files and Plots

The function for writing table-format files to your computer is write.table.

Example:

# You supply a data frame object as x, and this function writes its contents to
#a new file with a specified name, delimiter, and missing value string. For example, the following line takes the mydatafile object from Section 8.2 and writes it to a file:

#table.write<-write.table(x=mydatafile,file="C:/Users/hp/Downloads/8.2.1_mydatafile.txt",sep="@",na="??",quote=FALSE,row.names=FALSE)

data("iris")
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
which((iris$Species == "setosa"))
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
cat_r<-rnorm(c(4,2,3,8:16,19:20,1,5:7,18,17))
hist(cat_r)

summary(cat_r)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -1.2006 -0.2740  0.3804  0.3462  0.8567  1.9889
mean(cat_r)
## [1] 0.3462435
median(cat_r)
## [1] 0.3804476
summary(cat_r)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -1.2006 -0.2740  0.3804  0.3462  0.8567  1.9889

Friday 3rd October 2025.

Week 1

Combination of everything done through the week.

#install.packages("ks")

#library(ks)

#To install a package in R I'll have to use the command "install.package()"
#This gives the user a shortcut way to int=stall simply his/her package which
#Which is also known as "libraries of command"!

#The above package "ks" is just an example on how to install a package which I


#Knowing how to perform an assignment with R.
M <- rep(seq(1:3), time=2)

B <- print(!M)
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
print(!B)
## [1] TRUE TRUE TRUE TRUE TRUE TRUE
`my result` <- 91

print(`my result`)
## [1] 91
M <- seq(1:20)

K <- mean(M, trim=0.3, na.rm = FALSE)

print(K)
## [1] 10.5
J <- c("Alex", "John","Hassana", "Jumai", "Hajara")

print(J)
## [1] "Alex"    "John"    "Hassana" "Jumai"   "Hajara"
m <- matrix()


B <- c(2, 5, 13, 19, 11, 20)

print(B>10)
## [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE
#How to call an object
for (i in seq(1:10))

  print(i)
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
for (i in seq(2:28)) {
 print(i)
}
## [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
#Some Little work through matrix and mean with diag and mean functions.

A <- diag(x=3)
print(A)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1
#Example from the book of R, page 43.
d <- c(0:10,50)

dm <- mean(d)
v <- c(dm,mean(d, trim = 0.10))

print(v)
## [1] 8.75 5.50
print(d)
##  [1]  0  1  2  3  4  5  6  7  8  9 10 50
#Mean
F <- c(1,2,NA,5)
 mean(F)   #After running the code it results:[1] NA
## [1] NA
 #But when I return with a more explicit but reversed code for the mean, such as:
 mean(F,na.rm = TRUE)  #I got this result:[1] 2.666667
## [1] 2.666667
 #Where the na.rm means ("not available. remove"), which helps remove the NA
 #by the command "na.rm".


z <- c(0+6i, 1-9i, 2+0i, 8+15i, 1+2i)

Table <- data.frame(
  Complex = z,
  Imaginary = Im(z),
  Real = Re(z),
  Argument = Arg(z),
  Modulus = Mod(z),
  Conjugate = Conj(z)
)

print(Table)
##   Complex Imaginary Real  Argument   Modulus Conjugate
## 1   0+ 6i         6    0  1.570796  6.000000     0- 6i
## 2   1- 9i        -9    1 -1.460139  9.055385     1+ 9i
## 3   2+ 0i         0    2  0.000000  2.000000     2+ 0i
## 4   8+15i        15    8  1.080839 17.000000     8-15i
## 5   1+ 2i         2    1  1.107149  2.236068     1- 2i
#Basic plotting in R
foo<-1:5
bar<-6:10
baz <- cbind(foo,bar)

plot(baz)

#First Exercise: (a). Say the word cat aloud.

Alushi<-"Say the word cat aloud"

print(Alushi)
## [1] "Say the word cat aloud"
#Second Exercise: (b). Find the solution to 1+1

L<-1
O<-1
G<-L+O

print(G)
## [1] 2

Part (1)

Continuation of Chapter 2, Wed (6,8,2025)

# Sequence creation with rbind
Mycob <- c(rbind(seq(1,86), seq(6,91)))
print(Mycob)
##   [1]  1  6  2  7  3  8  4  9  5 10  6 11  7 12  8 13  9 14 10 15 11 16 12 17 13
##  [26] 18 14 19 15 20 16 21 17 22 18 23 19 24 20 25 21 26 22 27 23 28 24 29 25 30
##  [51] 26 31 27 32 28 33 29 34 30 35 31 36 32 37 33 38 34 39 35 40 36 41 37 42 38
##  [76] 43 39 44 40 45 41 46 42 47 43 48 44 49 45 50 46 51 47 52 48 53 49 54 50 55
## [101] 51 56 52 57 53 58 54 59 55 60 56 61 57 62 58 63 59 64 60 65 61 66 62 67 63
## [126] 68 64 69 65 70 66 71 67 72 68 73 69 74 70 75 71 76 72 77 73 78 74 79 75 80
## [151] 76 81 77 82 78 83 79 84 80 85 81 86 82 87 83 88 84 89 85 90 86 91
# Vector creation
Myvec <- c(1,3,1,42)
foo <- 32.1   # define foo before using
myvec2 <- c(3,-3,2,3.45,1e+03,64^0.5,2+(3-1.1)/9.44,foo)

# combinations of vectors
myvec3 <- c(Myvec,myvec2)
print(myvec3)
##  [1]    1.000000    3.000000    1.000000   42.000000    3.000000   -3.000000
##  [7]    2.000000    3.450000 1000.000000    8.000000    2.201271   32.100000
# Creation of sequence
myseq2 <- seq(from=foo,to=(-47+1.5),length.out=5)
print(myseq2)
## [1]  32.1  12.7  -6.7 -26.1 -45.5
# Repetition examples
rep(x=1,times=5)
## [1] 1 1 1 1 1
rep(x=c(1,2,3),times=3)
## [1] 1 2 3 1 2 3 1 2 3
rep(x=c(2,3,5),times=6,each=2)
##  [1] 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5 2 2 3 3 5 5
# Join sequences
goo <- 4
foo+1
## [1] 33.1
# Sorting
sort(x=c(2.5,-1,-10,3.44),decreasing = FALSE)
## [1] -10.00  -1.00   2.50   3.44
sort(x=c(2.5,-1,-10,3.44),decreasing = TRUE)
## [1]   3.44   2.50  -1.00 -10.00
foo <- seq(from=4.3,to=5.5,length.out=8)
foo
## [1] 4.300000 4.471429 4.642857 4.814286 4.985714 5.157143 5.328571 5.500000
bar <- sort(foo,decreasing=TRUE)
bar
## [1] 5.500000 5.328571 5.157143 4.985714 4.814286 4.642857 4.471429 4.300000
sort(c(foo,bar),decreasing=FALSE)
##  [1] 4.300000 4.300000 4.471429 4.471429 4.642857 4.642857 4.814286 4.814286
##  [9] 4.985714 4.985714 5.157143 5.157143 5.328571 5.328571 5.500000 5.500000
sort(c(foo,bar,goo),decreasing=FALSE)
##  [1] 4.000000 4.300000 4.300000 4.471429 4.471429 4.642857 4.642857 4.814286
##  [9] 4.814286 4.985714 4.985714 5.157143 5.157143 5.328571 5.328571 5.500000
## [17] 5.500000
A2 <- seq(from=3,to=27,length.out=40)
D <- sort(c(goo,foo,bar,A2),decreasing=TRUE)

# Added Work
S <- rnorm(n=57,mean=11.92,sd=7.619811)
sort(S,decreasing=FALSE)
##  [1] -1.8001016 -0.4027391  2.0572280  2.3252230  4.2504576  4.5419770
##  [7]  6.2504194  6.3295631  7.1737025  7.3133615  7.4768201  7.5618113
## [13]  7.7368282  7.8179745  8.1950001  8.8937426 10.1709655 10.2033278
## [19] 10.4527313 10.5432754 10.9863111 11.0395941 11.3623908 11.9153328
## [25] 12.0236545 12.0335417 12.3175379 13.2373445 13.9051114 15.4622089
## [31] 15.8238331 15.8876898 16.1925409 16.6362771 16.8198982 17.1777385
## [37] 17.2926236 17.6663737 17.8431943 18.7689889 18.8585098 18.9043976
## [43] 19.2455009 19.5427430 19.9827966 20.2678505 20.4455295 20.4877713
## [49] 20.8852439 21.0835042 21.8552267 22.0751055 22.0923493 24.0720108
## [55] 26.1428108 29.5829957 31.9796125
log(S)
## Warning in log(S): NaNs produced
##  [1]       NaN 2.9948717 2.4778260 1.5133624 2.8502800 1.4470267 2.9572773
##  [8] 2.4303088 2.8115857 1.9897030 2.7615172 2.8716630 2.3966501 2.0459918
## [15] 2.9726040 2.5110241 0.8438160 2.5830420 2.1035242 2.0118076 1.9704219
## [22] 0.7213595 2.3554882 2.3227139 2.8816222 3.4650986 2.8436143 2.7655446
## [29] 3.0844401 2.3468633 1.8452312 2.8225626 2.7845507 2.0231108 3.2635742
## [36] 2.9369643 2.9322060 3.3871997 3.0484909 2.9393946 2.3195371 3.0177643
## [43] 2.6322565 3.0090359       NaN 3.1810498 1.8326486 2.1853480 2.7383989
## [50] 3.0944505 3.0952314 3.0390429 2.4876979 2.0564255 3.0198282 2.4014883
## [57] 2.4868759
# Plotting
N <- seq_along(D)
plot(N,D,type="n",xlab="Azizi",ylab="Ayimo")

plot(S)

# Logs and exp
log(0.3)
## [1] -1.203973
log(0.3,base=2)
## [1] -1.736966
exp(-1.203973)
## [1] 0.2999999
# Save and load
save.image()
load(".Rdata")

# Factor example
ordfac.vec <- factor(
  c("small","Large","Large","Regular","Large"),
  levels=c("small","Regular","Large"),
  ordered=TRUE
)

# Arithmetic order example
X <- -5
X <- X+1

#Exercise 2.1
#(a)
a<-2.3
(6*a+42)/(3^(4.2-3.62))
## [1] 29.50556
#
#(b)i
(-4)^2+2
## [1] 18
#(ii)
-4^2+2
## [1] -14
#(iii)
(-4)^(2+2)
## [1] 256
#(iv)
-4^(2+2)
## [1] -256
#(c)
sqrt(((25.2+15+16.44+15.3+18.6)/5)*0.5)
## [1] 3.008987
#(d)
d<-log(0.3)

#(e)
exp(d)
## [1] 0.3
#(f)
print(-0.00000000423546322) #To see how R identify such a number in E-notation.
## [1] -4.235463e-09
# Exercise 2.2
t <- 3^2*4^(1/8)
z <- t/2.33
print(z)
## [1] 4.593504
m <- -8.2*10^(-13)
print(m)
## [1] -8.2e-13
print(z*m)
## [1] -3.766673e-12
# Example 2.3
Myvec <- c(1,3,1,42)
print(Myvec)
## [1]  1  3  1 42
foo <- 32.1
myvec2 <- c(3,-3,2,3.45,1e+03,64^0.5,2+(3-1.1)/9.44,foo)
print(myvec2)
## [1]    3.000000   -3.000000    2.000000    3.450000 1000.000000    8.000000
## [7]    2.201271   32.100000
myvec3 <- c(Myvec,myvec2)
print(myvec3)
##  [1]    1.000000    3.000000    1.000000   42.000000    3.000000   -3.000000
##  [7]    2.000000    3.450000 1000.000000    8.000000    2.201271   32.100000
# Exercise 2.3
myseqA <- seq(from=5,to=-11,by=-0.3)
rev(myseqA)
##  [1] -10.9 -10.6 -10.3 -10.0  -9.7  -9.4  -9.1  -8.8  -8.5  -8.2  -7.9  -7.6
## [13]  -7.3  -7.0  -6.7  -6.4  -6.1  -5.8  -5.5  -5.2  -4.9  -4.6  -4.3  -4.0
## [25]  -3.7  -3.4  -3.1  -2.8  -2.5  -2.2  -1.9  -1.6  -1.3  -1.0  -0.7  -0.4
## [37]  -0.1   0.2   0.5   0.8   1.1   1.4   1.7   2.0   2.3   2.6   2.9   3.2
## [49]   3.5   3.8   4.1   4.4   4.7   5.0
sort(myseqA,decreasing=TRUE)
##  [1]   5.0   4.7   4.4   4.1   3.8   3.5   3.2   2.9   2.6   2.3   2.0   1.7
## [13]   1.4   1.1   0.8   0.5   0.2  -0.1  -0.4  -0.7  -1.0  -1.3  -1.6  -1.9
## [25]  -2.2  -2.5  -2.8  -3.1  -3.4  -3.7  -4.0  -4.3  -4.6  -4.9  -5.2  -5.5
## [37]  -5.8  -6.1  -6.4  -6.7  -7.0  -7.3  -7.6  -7.9  -8.2  -8.5  -8.8  -9.1
## [49]  -9.4  -9.7 -10.0 -10.3 -10.6 -10.9
K <- rep(c(-1,3,-5,7,-9),time=2,each=10)
sort(K,decreasing=TRUE)
##   [1]  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  3  3  3  3  3
##  [26]  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
##  [51] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5
##  [76] -5 -5 -5 -5 -5 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9
J <- seq(6,12)
O <- rep(5.3,3)
T <- -3
P <- seq(102,100,length.out=9)
MyvectE <- c(J,O,T,P)
MyvectE
##  [1]   6.00   7.00   8.00   9.00  10.00  11.00  12.00   5.30   5.30   5.30
## [11]  -3.00 102.00 101.75 101.50 101.25 101.00 100.75 100.50 100.25 100.00
length(MyvectE)
## [1] 20
length(Myvec)
## [1] 4
foo <- Myvec[2]
Myvec[1]
## [1] 1
foo
## [1] 3
Myvec[length(Myvec)]
## [1] 42
myvec.len <- length(Myvec)
bar <- Myvec[myvec.len-1]
bar
## [1] 1
# Exercise 2.4
seq(3,6,length.out=5)
## [1] 3.00 3.75 4.50 5.25 6.00
z <- rep(c(2,-5.1,-33),times=2)
m <- (7/42)+2
v <- seq(3,6,length.out=5)
y <- v[1]
h <- z[1]
length(r<-m[1])
## [1] 1
length(y)
## [1] 1
length(z)
## [1] 6
length(v)
## [1] 5
tail(v,2)
## [1] 5.25 6.00
tail(m,1)
## [1] 2.166667
tail(z,1)
## [1] -33
r <- m[length(m)]
h <- z[length(z)]
h <- c(z[length(z)],z[1])
y <- c(v[length(v)],v[1])
f <- v[3:(length(v)-1)]
d <- z[3:(length(z)-1)]
q <- m[1:(length(m)-1)]
n <- seq(length(v),length(f),length.out=5)
u <- seq(length(z),length(d),length.out=5)
p <- seq(length(m),length(q),length.out=5)
w <- sort(v,decreasing=FALSE)
g <- sort(y,decreasing=FALSE)
b <- sort(m,decreasing=FALSE)
w[1:5]; g[2:1]; b[1:1]
## [1] 3.00 3.75 4.50 5.25 6.00
## [1] 6 3
## [1] 2.166667
sort(w,decreasing=TRUE)
## [1] 6.00 5.25 4.50 3.75 3.00
sort(g,decreasing=TRUE)
## [1] 6 3
sort(b,decreasing=TRUE)
## [1] 2.166667
# More sequence work
foo <- 5.3
bar <- foo:(-47.0+1.5)
print(bar)
##  [1]   5.3   4.3   3.3   2.3   1.3   0.3  -0.7  -1.7  -2.7  -3.7  -4.7  -5.7
## [13]  -6.7  -7.7  -8.7  -9.7 -10.7 -11.7 -12.7 -13.7 -14.7 -15.7 -16.7 -17.7
## [25] -18.7 -19.7 -20.7 -21.7 -22.7 -23.7 -24.7 -25.7 -26.7 -27.7 -28.7 -29.7
## [37] -30.7 -31.7 -32.7 -33.7 -34.7 -35.7 -36.7 -37.7 -38.7 -39.7 -40.7 -41.7
## [49] -42.7 -43.7 -44.7
A <- seq(from=3,to=27,by=3)
print(A)
## [1]  3  6  9 12 15 18 21 24 27
A2 <- seq(from=3,to=27,length.out=40)
print(A2)
##  [1]  3.000000  3.615385  4.230769  4.846154  5.461538  6.076923  6.692308
##  [8]  7.307692  7.923077  8.538462  9.153846  9.769231 10.384615 11.000000
## [15] 11.615385 12.230769 12.846154 13.461538 14.076923 14.692308 15.307692
## [22] 15.923077 16.538462 17.153846 17.769231 18.384615 19.000000 19.615385
## [29] 20.230769 20.846154 21.461538 22.076923 22.692308 23.307692 23.923077
## [36] 24.538462 25.153846 25.769231 26.384615 27.000000
myseq <- seq(from=foo,to=(-47.0+1.5),by=-2.4)
print(myseq)
##  [1]   5.3   2.9   0.5  -1.9  -4.3  -6.7  -9.1 -11.5 -13.9 -16.3 -18.7 -21.1
## [13] -23.5 -25.9 -28.3 -30.7 -33.1 -35.5 -37.9 -40.3 -42.7 -45.1
# Vector behavior
noo <- 5.5:0.5
noo
## [1] 5.5 4.5 3.5 2.5 1.5 0.5
noo-c(2,4,6,8,10,12)
## [1]   3.5   0.5  -2.5  -5.5  -8.5 -11.5
noo*c(1,-1,1,-1,1,-1)
## [1]  5.5 -4.5  3.5 -2.5  1.5 -0.5
mar <- c(1,-1)
noo*mar
## [1]  5.5 -4.5  3.5 -2.5  1.5 -0.5
qux <- 3
noo+qux
## [1] 8.5 7.5 6.5 5.5 4.5 3.5
noo+c(3)
## [1] 8.5 7.5 6.5 5.5 4.5 3.5
noo+rep(3,length(noo))
## [1] 8.5 7.5 6.5 5.5 4.5 3.5
noo[c(1,3,5,6)] <- c(-99,99)
noo
## [1] -99.0   4.5  99.0   2.5 -99.0  99.0
# Exercise 2.5
boo <- c(2,0.5,1,2,0.5,1,2,0.5,1)
boo <- boo/c(2,0.5,1)
boo
## [1] 1 1 1 1 1 1 1 1 1
vec <- rep(1,3)
c <- c(2,0.5,1)
var <- boo/c
var
## [1] 0.5 2.0 1.0 0.5 2.0 1.0 0.5 2.0 1.0
boo[1:length(boo)] <- vec
boo
## [1] 1 1 1 1 1 1 1 1 1
boo[length(boo)] <- c(rep(1,3))
## Warning in boo[length(boo)] <- c(rep(1, 3)): number of items to replace is not
## a multiple of replacement length
boo
## [1] 1 1 1 1 1 1 1 1 1
F <- c(45,77,20,19,101,120,212)
C <- (5/9)*(F-32)
C
## [1]   7.222222  25.000000  -6.666667  -7.222222  38.333333  48.888889 100.000000
moo <- rep(c(2,4,6),2)*rep(c(1,2),each=3)
moo
## [1]  2  4  6  4  8 12
moo[2:5] <- c(-0.1,-100)
moo
## [1]    2.0   -0.1 -100.0   -0.1 -100.0   12.0

Week 3

Monday 11th August 2025.

#Working with matrix command.
A<-matrix(data=c(-3,2,893,0.17),nrow=2,ncol=2)
A
##      [,1]   [,2]
## [1,]   -3 893.00
## [2,]    2   0.17
#Identical matrix
matrix(data=c(-3,2,893,0.17))
##        [,1]
## [1,]  -3.00
## [2,]   2.00
## [3,] 893.00
## [4,]   0.17
#Is the same as :
matrix(data=c(-3,2,893,0.17),nrow=4,ncol=1)
##        [,1]
## [1,]  -3.00
## [2,]   2.00
## [3,] 893.00
## [4,]   0.17
#Filling Direction
matrix(data=c(1,2,3,4,5,6),2,3,byrow=FALSE)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
#Now we change the direction by using "TRUE".
matrix(c(1,2,3,5,9,-0.5),2,3, TRUE)
##      [,1] [,2] [,3]
## [1,]    1    2  3.0
## [2,]    5    9 -0.5
#Row and Column Bindings
rbind(1:3,6:8)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    6    7    8
cbind(c(1,5),c(2,6),c(3,7))
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    5    6    7
#Matrix Dimension
mymat<-rbind(c(1,3,4),5:3,c(100,20,90),11:13)
mymat
##      [,1] [,2] [,3]
## [1,]    1    3    4
## [2,]    5    4    3
## [3,]  100   20   90
## [4,]   11   12   13
#To check dimension using "dim"
dim(mymat)
## [1] 4 3
nrow(mymat)
## [1] 4
ncol(mymat)
## [1] 3
dim(mymat)[2]
## [1] 3
#Sub-setting
B<-matrix(c(0.3,4.5,55.3,91,0.1,105.5,-4.2,8.2,27.9),nrow = 3,ncol = 3)
B
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  4.5   0.1  8.2
## [3,] 55.3 105.5 27.9
#Row,column,and Diagonal Extractions
B[,2] #This examines the second column.
## [1]  91.0   0.1 105.5
B[1,] #This examines the first row of the matrix.
## [1]  0.3 91.0 -4.2
#Using the Colon to indicate the values to be extracted.
B[2:3,]
##      [,1]  [,2] [,3]
## [1,]  4.5   0.1  8.2
## [2,] 55.3 105.5 27.9
B[,c(3,1)]
##      [,1] [,2]
## [1,] -4.2  0.3
## [2,]  8.2  4.5
## [3,] 27.9 55.3
# Adding arguments that can Work on the matrix.
B[c(3,1),2:3]
##       [,1] [,2]
## [1,] 105.5 27.9
## [2,]  91.0 -4.2
# identifying the values along the diagonal of a matrix.
diag(x=B)  #OR
## [1]  0.3  0.1 27.9
diag(B)
## [1]  0.3  0.1 27.9
# Omitting and Overwriting "Using the negative sign"
B[,-2]
##      [,1] [,2]
## [1,]  0.3 -4.2
## [2,]  4.5  8.2
## [3,] 55.3 27.9
# When I want to remove the first row and then Extracting Elements of B from 3:2
B[-1,3:2]
##      [,1]  [,2]
## [1,]  8.2   0.1
## [2,] 27.9 105.5
# The following removes the first row and second column of B.
B[-1,-2]
##      [,1] [,2]
## [1,]  4.5  8.2
## [2,] 55.3 27.9
B[-1,-c(2,3)]   # Delete first row, then second and the third columns respectively.
## [1]  4.5 55.3
#Overwriting an element, or entire rows or columns, you identify the elements to
#be replaced and then assign the new values.


C<-B
C
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  4.5   0.1  8.2
## [3,] 55.3 105.5 27.9
#Then following overwriting the second row of B
C[2,]<-1:3 #or  C[,2]<-1:3
C
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  1.0   2.0  3.0
## [3,] 55.3 105.5 27.9
C[c(1,3),2]<-900  #This means replace the first and third elements of C making
#sure it's on the second column with 900.

C
##      [,1] [,2] [,3]
## [1,]  0.3  900 -4.2
## [2,]  1.0    2  3.0
## [3,] 55.3  900 27.9
C[,3]<-C[3,]
C
##      [,1] [,2]  [,3]
## [1,]  0.3  900  55.3
## [2,]  1.0    2 900.0
## [3,] 55.3  900  27.9
# CONSIDERING Both row and column at the same time.
C[c(1,3),c(1,3)]<-c(-7,7)
C
##      [,1] [,2] [,3]
## [1,]   -7  900   -7
## [2,]    1    2  900
## [3,]    7  900    7
#Starting from column unto the rows assignes.
C[c(1,3),2:1]<-c(65,-65,88,-88)
C
##      [,1] [,2] [,3]
## [1,]   88   65   -7
## [2,]    1    2  900
## [3,]  -88  -65    7
#Changing the values of the diagonal of a matrix
diag(x=C)<-rep(0,3)
C
##      [,1] [,2] [,3]
## [1,]    0   65   -7
## [2,]    1    0  900
## [3,]  -88  -65    0

Tuesday 12th August 2025.

#Matrix operations and Algebra

#3.3.1 Matrix Transpose

S<-rbind(c(2,5,2),c(6,1,4))
t(S)
##      [,1] [,2]
## [1,]    2    6
## [2,]    5    1
## [3,]    2    4
S
##      [,1] [,2] [,3]
## [1,]    2    5    2
## [2,]    6    1    4
t(t(t(S)))
##      [,1] [,2]
## [1,]    2    6
## [2,]    5    1
## [3,]    2    4
#Identity matrix

A<-diag(3)   #Creates a square Identity matrix of 3 by 3 dimension.
A
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1
#Scalar multiple of a matrix
2*A  #Using a scalar say "x" to multiply a given vector say "A"
##      [,1] [,2] [,3]
## [1,]    2    0    0
## [2,]    0    2    0
## [3,]    0    0    2
2*S
##      [,1] [,2] [,3]
## [1,]    4   10    4
## [2,]   12    2    8
#Matrix addition and subtraction
D<-cbind(c(-2,3,6),c(8.1,8.2,-9.8))
E<-cbind(c(2,5,2),c(6,1,4))
E-D
##      [,1] [,2]
## [1,]    4 -2.1
## [2,]    2 -7.2
## [3,]   -4 13.8
#Matrix Multiplication
E<-rbind(c(2,5,2),c(6,1,4))
F<-cbind(c(3,-1,1),c(-3,1,5))
dim(E)
## [1] 2 3
dim(F)
## [1] 3 2
#They are compatible.
E%*%F
##      [,1] [,2]
## [1,]    3    9
## [2,]   21    3
F%*%E
##      [,1] [,2] [,3]
## [1,]  -12   12   -6
## [2,]    4   -4    2
## [3,]   32   10   22
#Note that Matrix multiplication is not commutative (i.e, when their positions
#changes the result to different values entirely).


#Inverse of a Matrix OR Matrix Inversion
A<-matrix(c(3,4,1,2),2,2)
A
##      [,1] [,2]
## [1,]    3    1
## [2,]    4    2
Q<-solve(A)   #The solve command is used to invert a matrix or simply to find the
#inverse of a Matrix.

#Verifying if the inverse is correct
A%*%Q   #Confirmed.
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
# Multidimensional Arrays

AR<-array(data=1:24,dim=c(3,4,2))
AR
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
#Note that (row,column,layer)
#Including the dimension of an array.
BR<-array(rep(1:24,3),dim=c(3,4,2,3))
BR
## , , 1, 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2, 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 1, 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2, 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 1, 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2, 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
#Note that (row,column,layer,blocks) connected to "dim'

#Subsets, Extractions, and Replacements
AR[2,,2]
## [1] 14 17 20 23
AR[2,c(3,1),2]
## [1] 20 14
# If I require only one output then:
AR[1,,]
##      [,1] [,2]
## [1,]    1   13
## [2,]    4   16
## [3,]    7   19
## [4,]   10   22
#and
BR[,,2,]
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
## 
## , , 3
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
# When it has to do with two independent values.
BR[3:2,4,,]
## , , 1
## 
##      [,1] [,2]
## [1,]   12   24
## [2,]   11   23
## 
## , , 2
## 
##      [,1] [,2]
## [1,]   12   24
## [2,]   11   23
## 
## , , 3
## 
##      [,1] [,2]
## [1,]   12   24
## [2,]   11   23
BR[2,,1,]
##      [,1] [,2] [,3]
## [1,]    2    2    2
## [2,]    5    5    5
## [3,]    8    8    8
## [4,]   11   11   11
#Important Codes
#rbind
#cbind
#dim
#nrow
#ncol
#[ , ]
#diag
#t
#*
#  +,
#%*%
 # solve
#array.

#Exercise 3.1
#Solutions
#(a)
a<-matrix(c(4.3,3.1,8.2,8.2,3.2,0.9,1.6,6.5),4,2,byrow = TRUE)
a
##      [,1] [,2]
## [1,]  4.3  3.1
## [2,]  8.2  8.2
## [3,]  3.2  0.9
## [4,]  1.6  6.5
#(b)
dim(a[-1,])
## [1] 3 2
#(c)
a[,2]<-sort(a[,2],decreasing = FALSE)
a
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#(d)
matrix(a[-4,-1])
##      [,1]
## [1,]  0.9
## [2,]  3.1
## [3,]  6.5
a
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#(e)
d<-matrix(a[(3:4),],2,2)
d
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
#(f)
vals <- -(1/2) * diag(d)
a[4,2] <- vals[1]
a[1,2] <- vals[2]
a[4,1] <- vals[1]
a[1,1] <- vals[2]
a
##      [,1] [,2]
## [1,] -4.1 -4.1
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,] -1.6 -1.6
# Or
a[rbind(c(4,2),c(1,2),c(4,1),c(1,1))]<-(-(1/2)*diag(b))
a
##      [,1] [,2]
## [1,] -0.5  0.0
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  0.0 -0.5
a[c(4,1),c(2,1)]<- -(1/2)*diag(b)
a
##      [,1] [,2]
## [1,] -0.5  0.0
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  0.0 -0.5
#(a) #creating the vector
A<-matrix(c(4.3,3.1,8.2,8.2,3.2,0.9,1.6,6.5),4,2,byrow=T)
A
##      [,1] [,2]
## [1,]  4.3  3.1
## [2,]  8.2  8.2
## [3,]  3.2  0.9
## [4,]  1.6  6.5
#(b) #confirming the dimension
dim(A[-1,])
## [1] 3 2
#(c)
A[,2]<-sort(A[,2],decreasing = FALSE)
B<-A
B
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#(d)
matrix(B[-4,-1])
##      [,1]
## [1,]  0.9
## [2,]  3.1
## [3,]  6.5
#(e)
C<-B[c(3,4),]
C
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
B[c(length(B)-5,length(B)-4),]
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
B[c(3:4),]
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
B[-c(1:2),]
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
#(f)
B[c(4,1),c(2,1)]<--(1/2)*diag(C)
B
##      [,1] [,2]
## [1,] -4.1 -4.1
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,] -1.6 -1.6

Wednesday 13th August 2025.

#Non numeric values: Logical, Character and Factors.

#4.0 Logical
foo<-TRUE
foo
## [1] TRUE
bar<-FALSE
bar
## [1] FALSE
bar
## [1] FALSE
#Filling a vector with logical values.
baz<-c(T,F,F,F,T,F,T,T,T,F,T,F)
baz
##  [1] -3  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5 -3  3 -1  1 -3  1
## [26]  5 -3 -3 -3  3 -1  1 -3  1  5 -3  3 -1  1 -3  1  5
length(baz)
## [1] 42
#Creating matrix with logical data types.
qux<-matrix(baz,nrow = 3,ncol=4,byrow=foo)
## Warning in matrix(baz, nrow = 3, ncol = 4, byrow = foo): data length [42] is
## not a sub-multiple or multiple of the number of columns [4]
qux
##      [,1] [,2] [,3] [,4]
## [1,]   -3    3   -1    1
## [2,]   -3    1    5    3
## [3,]   -1    1   -3    1
#A Logical outcome: Relational operators
1==2
## [1] FALSE
1>2
## [1] FALSE
(2-1)<=2
## [1] TRUE
1!=(2+3)
## [1] TRUE
#Checking if the length of two different vectors are the same or not.
foo<-c(3,2,1,4,1,2,1,-1,0,3)
bar<-c(4,1,2,1,1,0,0,3,0,4)

#Checking
length(foo)==length(bar)
## [1] TRUE
#Consider the following evaluations
foo==bar  #Checking to see whether the are equal.
##  [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
foo<bar
##  [1]  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE
foo<=bar
##  [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE
foo<=(bar+10)
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#Recycling my Vectors
baz<-foo[c(10,3)]
baz
## [1] 3 1
foo<3
##  [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
#Let us now create a matrix with our objects
foo.mat<-matrix(foo,5,2)
foo.mat
##      [,1] [,2]
## [1,]    3    2
## [2,]    2    1
## [3,]    1   -1
## [4,]    4    0
## [5,]    1    3
bar.mat<-matrix(bar,5,2)
bar.mat
##      [,1] [,2]
## [1,]    4    0
## [2,]    1    0
## [3,]    2    3
## [4,]    1    0
## [5,]    1    4
#Comparing the two matrices with logical operators.
foo.mat<bar.mat
##       [,1]  [,2]
## [1,]  TRUE FALSE
## [2,] FALSE FALSE
## [3,]  TRUE  TRUE
## [4,] FALSE FALSE
## [5,] FALSE  TRUE
foo.mat<3
##       [,1]  [,2]
## [1,] FALSE  TRUE
## [2,]  TRUE  TRUE
## [3,]  TRUE  TRUE
## [4,] FALSE  TRUE
## [5,]  TRUE FALSE
#Forming a logical vector using the logical operators.
qux<-foo==bar
qux
##  [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
any(qux)
## [1] TRUE
all(qux)
## [1] FALSE
#Following the same rules
quux<-foo<=(bar+10)
quux
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
any(quux)
## [1] TRUE
all(quux)
## [1] TRUE
#Exercise 3.2
#Solutions
#(a)
(2/7)*((cbind(c(1,2,7),c(2,4,6)))-(cbind(c(10,30,50),c(20,40,60))))
##            [,1]       [,2]
## [1,]  -2.571429  -5.142857
## [2,]  -8.000000 -10.285714
## [3,] -12.285714 -15.428571
#(b)
A<-cbind(c(1,2,7))
B<-cbind(c(3,4,8))

#ii.
t(A)%*%B
##      [,1]
## [1,]   67
#iii.
t(B)%*%(A%*%t(A))
##      [,1] [,2] [,3]
## [1,]   67  134  469
#iv.
R<-(A%*%t(A))
T<-t(B)
#Not possible
#R*T
#(A%*%t(A))%*%t(B)


#v.
solve((B%*%t(B)+(A%*%t(A)-100*(diag(3)))))
##              [,1]         [,2]        [,3]
## [1,] -0.007923676  0.003123274 0.007843334
## [2,]  0.003123274 -0.005350239 0.011483806
## [3,]  0.007843334  0.011483806 0.017584735
#(c)
A<-(cbind(c(2,0,0,0),c(0,3,0,0),c(0,0,5,0),c(0,0,0,-1)))
A
##      [,1] [,2] [,3] [,4]
## [1,]    2    0    0    0
## [2,]    0    3    0    0
## [3,]    0    0    5    0
## [4,]    0    0    0   -1
(solve(A)%*%A)-diag(4) # Confirmed.
##      [,1] [,2] [,3] [,4]
## [1,]    0    0    0    0
## [2,]    0    0    0    0
## [3,]    0    0    0    0
## [4,]    0    0    0    0

Thursday 14th August 2025.

#Multiple Comparisons: Logical Operators
#FALSE||((T&&T)||FALSE)
!TRUE&&TRUE
## [1] FALSE
#(T&&(T||F))&&FALSE
(6<4)||(3!=1)
## [1] TRUE
#
(6<3)||(3!=1)||(9>1)
## [1] TRUE
#Element-wise examples
foo<-c(T,F,F,F,T,F,T,T,T,F,T,F)
foo
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8  3
## [26] -1  1 -3  1  5  3  4  8  3  4  8  3  4  8  3 -1  1 -3  1  5  3  4  8  3 -1
## [51]  1 -3  1  5
bar<-c(F,T,F,T,F,F,F,F,T,T,T,T)
bar
##  [1]  3 -1  1 -3  1  5  3  4  8  3 -1  1 -3  1  5  3  4  8  3 -1  1 -3  1  5  3
## [26] -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8  3  4  8  3  4
## [51]  8  3  4  8
#Comparing vector to vector element-wise
foo&bar # Using the short comparator.
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [46] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#Comparing vector to vector using the long comparator.
foo[1]&&bar[1]
## [1] TRUE
foo[1]||bar[1]
## [1] TRUE
#Exercise 3.3
#Solutions.
#(a)
A<-array(4.8:0.1,dim=c(4,2,6))
A
## , , 1
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  3.8  4.8
## [2,]  2.8  3.8
## [3,]  1.8  2.8
## [4,]  0.8  1.8
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1] [,2]
## [1,]  2.8  3.8
## [2,]  1.8  2.8
## [3,]  0.8  1.8
## [4,]  4.8  0.8
## 
## , , 6
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
#(b)
B<-A[c(4,1),2,]
B
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]  2.8  4.8  1.8  3.8  0.8  2.8
## [2,]  0.8  2.8  4.8  1.8  3.8  0.8
#(c)
C<-array(rep(B[2,],4),dim=c(2,2,2,3))
C
## , , 1, 1
## 
##      [,1] [,2]
## [1,]  0.8  4.8
## [2,]  2.8  1.8
## 
## , , 2, 1
## 
##      [,1] [,2]
## [1,]  3.8  0.8
## [2,]  0.8  2.8
## 
## , , 1, 2
## 
##      [,1] [,2]
## [1,]  4.8  3.8
## [2,]  1.8  0.8
## 
## , , 2, 2
## 
##      [,1] [,2]
## [1,]  0.8  4.8
## [2,]  2.8  1.8
## 
## , , 1, 3
## 
##      [,1] [,2]
## [1,]  3.8  0.8
## [2,]  0.8  2.8
## 
## , , 2, 3
## 
##      [,1] [,2]
## [1,]  4.8  3.8
## [2,]  1.8  0.8
#The first thing I did was to first check the dimension of B.
# so that I can find the appropriate argument for sub-setting.

#(d)
D<-A[,,-6]
D
## , , 1
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  3.8  4.8
## [2,]  2.8  3.8
## [3,]  1.8  2.8
## [4,]  0.8  1.8
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1] [,2]
## [1,]  2.8  3.8
## [2,]  1.8  2.8
## [3,]  0.8  1.8
## [4,]  4.8  0.8
D<-array(A,dim=c(4,2,(6-1)))
D
## , , 1
## 
##      [,1] [,2]
## [1,]  4.8  0.8
## [2,]  3.8  4.8
## [3,]  2.8  3.8
## [4,]  1.8  2.8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  3.8  4.8
## [2,]  2.8  3.8
## [3,]  1.8  2.8
## [4,]  0.8  1.8
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1] [,2]
## [1,]  2.8  3.8
## [2,]  1.8  2.8
## [3,]  0.8  1.8
## [4,]  4.8  0.8
#(e)
D[c(2,4),2,c(1,3,5)]<--99
D
## , , 1
## 
##      [,1]  [,2]
## [1,]  4.8   0.8
## [2,]  3.8 -99.0
## [3,]  2.8   3.8
## [4,]  1.8 -99.0
## 
## , , 2
## 
##      [,1] [,2]
## [1,]  1.8  2.8
## [2,]  0.8  1.8
## [3,]  4.8  0.8
## [4,]  3.8  4.8
## 
## , , 3
## 
##      [,1]  [,2]
## [1,]  3.8   4.8
## [2,]  2.8 -99.0
## [3,]  1.8   2.8
## [4,]  0.8 -99.0
## 
## , , 4
## 
##      [,1] [,2]
## [1,]  0.8  1.8
## [2,]  4.8  0.8
## [3,]  3.8  4.8
## [4,]  2.8  3.8
## 
## , , 5
## 
##      [,1]  [,2]
## [1,]  2.8   3.8
## [2,]  1.8 -99.0
## [3,]  0.8   1.8
## [4,]  4.8 -99.0

Friday 15th August 2025.

#Logical Are Numbers!
TRUE+TRUE
## [1] 2
FALSE-TRUE  #PERFORMING ELEMENTARY NUMERIC OPERATIONS ON lOGICAL VALUES
## [1] -1
#T+T+F+T+F+F+T

#Substituting numerical values for logical values
1&&1
## [1] TRUE
1||0
## [1] TRUE
0&&1
## [1] FALSE
#Logical Sub-setting and Extraction.
myvec<-c(5,-2.3,4,4,4,6,8,10,40221,-8)
myvec[c(2,10)] #Or
## [1] -2.3 -8.0
#myvec[c(F,T,F,F,F,F,F,F,F,T)]
#Together the above code results to the negative vales. considering the
#The second code the values that are changed to be TRUTH  values are those that are extracted.

#Checking negative numeric values with logical relationals
myvec<0
##  [1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
#Sub-setting some certain values from a vector using logical ralation and numeric values
myvec[myvec<0]
## [1] -2.3 -8.0
#To extract the second values after the first values we use the :

#myvec[c(T,F)]

#And myvec[F,T] for second values beginning from the second term.
#More complicated extraction with relational and logical operators.
myvec[(myvec>0)&(myvec<100)]
## [1]  5  4  4  4  6  8 10
#Overwriting the values in the vector
myvec[myvec<0]<-(-200)
myvec
##  [1]     5  -200     4     4     4     6     8    10 40221  -200
#Changing Logical flags vector into numeric vectors with "which" function.

#which(x=c(T,F,F,T,T))

#Changing those values of myvec that satisfies the <0 criteria.
which(x=myvec<0)
## [1]  2 10
#To delete elements based on logical flags I can use the following:
myvec[-which(x=myvec<0)]
## [1]     5     4     4     4     6     8    10 40221
myvec[-which(x=myvec>0)]
## [1] -200 -200
#Exercise 4.1
#Solutions
#(a)
A<-c(6,9,7,3,6,7,9,6,3,6,6,7,1,9,1)

#To identify the above mention, we do:
#i.
A[A==6] #Those equal to 6
## [1] 6 6 6 6 6
#ii.
A[A>=6]  #Those greater than or equal to 6
##  [1] 6 9 7 6 7 9 6 6 6 7 9
#iii.
A[A<=(6+2)]  # Those less than 6+2
##  [1] 6 7 3 6 7 6 3 6 6 7 1 1
#iv.
A[A!=6]  # Those not equal to 6
##  [1] 9 7 3 7 9 3 7 1 9 1
#(b)
B<-c(A[-c(1:3)],dim=c(2,2,3))
B
##                                                             dim1 dim2 dim3 
##    3    6    7    9    6    3    6    6    7    1    9    1    2    2    3
#i. #Examining those less than or equal to 6/2 +4
B[B<=(6/2)+4]
##                                                   dim1 dim2 dim3 
##    3    6    7    6    3    6    6    7    1    1    2    2    3
#ii.
(B+2)[B<=(6/2)+4] #OR Q<-B+2
##                                                   dim1 dim2 dim3 
##    5    8    9    8    5    8    8    9    3    3    4    4    5
                 #Q[B<=(6/2)+4]

#(c)
C<-diag(10)  # Creating a 10by10 Identical matrix
which(C==0)  #identifying specific positions of values equal to 0
##  [1]  2  3  4  5  6  7  8  9 10 11 13 14 15 16 17 18 19 20 21 22 24 25 26 27 28
## [26] 29 30 31 32 33 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55
## [51] 57 58 59 60 61 62 63 64 65 66 68 69 70 71 72 73 74 75 76 77 79 80 81 82 83
## [76] 84 85 86 87 88 90 91 92 93 94 95 96 97 98 99
#(d)
any(B)  #Yes they are TRUE
## Warning in any(B): coercing argument of type 'double' to logical
## [1] TRUE
all(B)
## Warning in all(B): coercing argument of type 'double' to logical
## [1] TRUE
#(e)
R<-C[diag(C)]
any(R)
## Warning in any(R): coercing argument of type 'double' to logical
## [1] TRUE
#Exercise 4.2
#EXERCISE 4.2
#Solutions.

#(a) #To Identify elements >5 |==2
foo<-c(7,1,7,10,5,9,10,3,10,8)
foo[(foo>5)|(foo==2)]
## [1]  7  7 10  9 10 10  8
#a<-foo[(foo>5)|(foo==2)]
#(b)  #Identifying elements <=6&!=4
bar<-c(8,8,4,4,5,1,5,6,6,8)
bar[(bar<=6)&(bar!=4)]
## [1] 5 1 5 6 6
#b<-bar[(bar<=6)&(bar!=4)]
#(c)
#foo[a[1]]&&bar[b[1]]
#foo[1:(length(a)-2)]&bar[b]

#which((foo[a])&(bar[b]))  #This I assumed to be the answer.

#(d)
baz<-foo+bar
baz
##  [1] 15  9 11 14 10 10 15  9 16 16
#i.
baz[(baz>=14)&(baz!=15)]
## [1] 14 16 16
#ii.
c<-(baz/foo)
baz[((baz/foo)>4)|((baz/foo)<=2)]
## [1]  9 11 14 10 10 15 16 16
#c[(c>4)|(c<=2)]

#(e)
#c[(c>4)||(c<=2)]
#c[(c>4)&&(c<=2)]

Week 4

Monday 18th August 2025.

#Extraction of numeric values using logical values
A<-matrix(c(0.3,4.5,55.3,91,0.1,105.5,-4.2,8.2,27.9),nrow=3,ncol=3)
A
##      [,1]  [,2] [,3]
## [1,]  0.3  91.0 -4.2
## [2,]  4.5   0.1  8.2
## [3,] 55.3 105.5 27.9
#To extract the second and third column elements of the first row of A, I can use or execute: A
A[1,2:3]  #OR
## [1] 91.0 -4.2
A[1,c(2,3)]
## [1] 91.0 -4.2
#But with logical values we can execute the following:

#A[c(T,F,F),c(F,T,T)]

#Logical flags application
A<1
##       [,1]  [,2]  [,3]
## [1,]  TRUE FALSE  TRUE
## [2,] FALSE  TRUE FALSE
## [3,] FALSE FALSE FALSE
A[A<1]<-(-7)
A
##      [,1]  [,2] [,3]
## [1,] -7.0  91.0 -7.0
## [2,]  4.5  -7.0  8.2
## [3,] 55.3 105.5 27.9
#Replacing values in a matrix using the index format alongside logical flags

#Finding the index position of elements in a matrix using logical flags.
A>25
##       [,1]  [,2]  [,3]
## [1,] FALSE  TRUE FALSE
## [2,] FALSE FALSE FALSE
## [3,]  TRUE  TRUE  TRUE
which(A>25)
## [1] 3 4 6 9
#Note that the which function in R is  mostly use to obtain the position of element in a vectoror matrx

#Checking this the other way round, because R count default column wise.
which(x=c(A[,1],A[,2],A[,3])>25)
## [1] 3 4 6 9
#Placing an array indexes TRUE or FALSE , in order to obtain the row and column index number of the element we seek their positions.
which(A>25, arr.ind=T)
## [1] 3 4 6 9
#section 4.2
#Creating a string
foo<-"This is a character string!"
foo
## [1] "This is a character string!"
length(foo)
## [1] 1
#Using "nchar" function to count the number of charecters in a string
nchar(foo)
## [1] 27
#String numeric characters are not the norminal numeric values, Hence this:
bar<-"23.3"
bar
## [1] "23.3"
#An attempt to multiply this value with a constant numeric value will only return an error.
#(bar*2)

#Comparing string values
"alpha"=="alpha"
## [1] TRUE
"alpha"!="beta"
## [1] TRUE
c("alpha","beta","gamma")=="beta"
## [1] FALSE  TRUE FALSE
#Other comparison
"gamma">"Alpha"
## [1] TRUE
#Considering lowercase vs. uppercase
"Alpha">"alpha"
## [1] TRUE
"beta">="bEtA"
## [1] FALSE
#Using special characters
baz<-"&4_3**%?$ymbolic non$en$e,;"
baz
## [1] "&4_3**%?$ymbolic non$en$e,;"
#Use the "cat" and "paste" functions.
qux<-c("awesome","R","is")
length(qux)
## [1] 3
qux
## [1] "awesome" "R"       "is"
#Calling "cat" or "paste" functions.
cat(qux[2],qux[3],"totally",qux[1],"!")
## R is totally awesome !
paste(qux[2],qux[3],"totally",qux[1],"!")
## [1] "R is totally awesome !"
#Want to separate using the "sep" function.
paste(qux[2],qux[3],"totally",qux[1],"!",sep="---")
## [1] "R---is---totally---awesome---!"
paste(qux[2],qux[3],"totally",qux[1],"!",sep="")
## [1] "Ristotallyawesome!"
#Using manual insertion of spacing where necessary.
cat("Do yo think ",qux[2]," ",qux[3]," ",qux[1],"?",sep="")
## Do yo think R is awesome?
#Passing many R objects with the "cat" and "paste" function as an object.
a<-3
b<-4.4
cat("The value stored as 'a' is ",a,".",sep="")
## The value stored as 'a' is 3.
paste("The value stored as 'b' is ",b,".",sep="")
## [1] "The value stored as 'b' is 4.4."
#Performing some little clculations
cat("The result of a+b is ",a,"+",b,"=",a+b,".",sep="")
## The result of a+b is 3+4.4=7.4.
paste("Is ",a+b," less than 10? That's totally ",a+b<10,".",sep="")
## [1] "Is 7.4 less than 10? That's totally TRUE."
#Spacing using the escape sequence.
cat("here is a string\nsplit\tto new\b\n\n\tlines")
## here is a string
## split    to new
## 
##  lines
#Using the escape signal to inculcate the backslash and the quotation sign.
cat("I really want a backslash: \\\nand a double quote: \"")
## I really want a backslash: \
## and a double quote: "
cat("I would love to have a double backslash:\\\nand a qoute:\"")
## I would love to have a double backslash:\
## and a qoute:"
cat("Mr Ade said, \"He lost his father on Wednesday\" \nbut the Principal couldn't allow him to go home that very day.\n What a tragedy!")
## Mr Ade said, "He lost his father on Wednesday" 
## but the Principal couldn't allow him to go home that very day.
##  What a tragedy!
#Note the following:
#(\n, \b, \t, \", and \\).

#setwd("/folder1/folder2/folder3/")


#Using the function "substr" to extract some certain values of choice.
foo<-"This is a character string!"
foo
## [1] "This is a character string!"
substr(foo,21,27)
## [1] "string!"
#Replacing extracted values
substr(foo,1,4)<-"Here"

#Substitution with "sub" and "gsub" function.
bar<-"How much wood could a woodchuck chuck"
sub(pattern="chuk",replacement="hurl",x=bar)
## [1] "How much wood could a woodchuck chuck"
gsub(pattern="chuck",replacement = "hurl",x=bar)
## [1] "How much wood could a woodhurl hurl"
cat("Martha ","sat ","at the foot of ","Jesus ","only to hear Him speak to her",sep="")
## Martha sat at the foot of Jesus only to hear Him speak to her

Tuesday 19th August 2025.

#Exercise 4.3
#(Solutions).
#(a)
#Storing the vectors as provided.
#i.
foo<-c(7,5,6,1,2,10,8,3,8,2)
bar<-(foo[(foo>=5)])
bar
## [1]  7  5  6 10  8  8
#ii.
foo[(-(foo>=5))]
## [1]  5  6  1  2 10  8  3  8  2
#(b)
#i.
baz<-matrix(bar,2,3,byrow=T)
baz
##      [,1] [,2] [,3]
## [1,]    7    5    6
## [2,]   10    8    8
#ii.
a<-sqrt(baz[1,2])
a
## [1] 2.236068
baz[baz==8]<-a
baz
##      [,1]     [,2]     [,3]
## [1,]    7 5.000000 6.000000
## [2,]   10 2.236068 2.236068
#ii.
#Confirming that all values in baz are <=25 and grater than 4
baz[(baz<=25)&(baz>4)]
## [1]  7 10  5  6
#(c)
#i.
qux<-array(c(10,5,1,4,7,4,3,3,1,3,4,3,1,7,8,3,7,3),dim=c(3,2,3))
which(qux==(3||4),arr.ind = T)
## [1]  3  9 13
#ii.
qux[(qux<3)|(qux>=7)]<-100
qux
## , , 1
## 
##      [,1] [,2]
## [1,]  100    4
## [2,]    5  100
## [3,]  100    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    3    3
## [2,]    3    4
## [3,]  100    3
## 
## , , 3
## 
##      [,1] [,2]
## [1,]  100    3
## [2,]  100  100
## [3,]  100    3
#(d)
#foo[c(F,T)]

#Trying to see whether 0 and 1 can work in this case
foo[c(0,1)]
## [1] 7
#WE cannot!
#Logical values is repeated over the given elements evenly. while numeric argument for indexing 0,1 extracts only the first appoint value. Thats why in this case R picks the second argument and ignore the first argument because it is 0.

Wednesday 20th September 2025.

#Section 4.3
#Factors
firstname<-c("Liz","Jolene","Susan","Boris","Rochelle","Tim","Simon","Amy")
sex.num<-c(0,0,0,1,0,1,1,0)
sex.char<-c("female","female","female","male","female","male","male","female")

#Creating a factor vector using the "factor" function.
sex.num.fac<-factor(x=sex.num)
sex.num.fac
## [1] 0 0 0 1 0 1 1 0
## Levels: 0 1
sex.char.fac<-factor(sex.char)
sex.char.fac
## [1] female female female male   female male   male   female
## Levels: female male
#Extracting the levels of a factor vector
levels(x=sex.num.fac)
## [1] "0" "1"
levels(x=sex.char.fac)
## [1] "female" "male"
#Relabeling the factor using "levels" function.
levels(x=sex.num.fac)<-c("1","2")
sex.num.fac
## [1] 1 1 1 2 1 2 2 1
## Levels: 1 2
#Sub-setting
sex.char.fac[2:5]
## [1] female female male   female
## Levels: female male
sex.char.fac[c(1:3,5,8)]
## [1] female female female female female
## Levels: female male
sex.char.fac
## [1] female female female male   female male   male   female
## Levels: female male
#Using Logical flags on factor.
sex.num.fac=="2"   #Note that you must use string (quotation mark) to identify the numeric levels of a factor.
## [1] FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE
#Using Logical flags to obtain certain values from two or more factor vector.
firstname[sex.char.fac=="male"]
## [1] "Boris" "Tim"   "Simon"
firstname[sex.char.fac=="female"]
## [1] "Liz"      "Jolene"   "Susan"    "Rochelle" "Amy"
firstname[sex.char=="female"]
## [1] "Liz"      "Jolene"   "Susan"    "Rochelle" "Amy"
firstname[sex.num=="1"]
## [1] "Boris" "Tim"   "Simon"
firstname[sex.num=="0"]
## [1] "Liz"      "Jolene"   "Susan"    "Rochelle" "Amy"
#Defining and Ordering Levels
mob<-c("Apr","Jan","Dec","Sep","Nov","Jul","Jul","Jun")
mob[2]
## [1] "Jan"
mob[3]
## [1] "Dec"
mob[2]<mob[3]
## [1] FALSE
#Defining levels in details now: Using the "levels" and "ordered" function respectively.
ms<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
#mob.fac<-factor(x=mob,levels=ms,ordered = TRUE)
#mob.fac

#Performing Relational comparison
#mob.fac[2]
#mob.fac[3]

# And again
#(mob.fac[2])<(mob.fac[3])
#Combing and cutting
foo<-c(5.1,3.3,3.1,4)
bar<-c(4.5,1.2)
c(foo,bar)
## [1] 5.1 3.3 3.1 4.0 4.5 1.2
#Another format
#new.values<-factor(x=c("Oct","Feb","Feb"),levels=levels(mob.fac),ordered=TRUE)
#new.values

#Now combining the two vectors together.
#c(mob.fac,new.values)

#Checking the index of each month
#levels(mob.fac)

#Extraction
#levels(mob.fac)[c(mob.fac,new.values)]
#mob.new<-levels(mob.fac)[c(mob.fac,new.values)]
#mob.new.fac<-factor(x=mob.new,levels = levels(mob.fac),ordered = TRUE)
#mob.new.fac

#Taking an Example
Y<-c(0.53,5.4,1.5,3.33,0.45,0.01,2,4.2,1.99,1.01)

#Using the "cut" to give intervals to the values in a vector.
br<-c(0,2,4,6)
cut(x=Y,breaks=br)
##  [1] (0,2] (4,6] (0,2] (2,4] (0,2] (0,2] (0,2] (4,6] (0,2] (0,2]
## Levels: (0,2] (2,4] (4,6]
#Setting the boundaries axis , making the upper bound be at the left.

#cut(x=Y,breaks=br,right=FALSE)
#cut(x=Y,breaks=br,right=FALSE,include.lowest=T)

#Including a label with "labels" function
lab<-c("Small","Medium","Large")
#cut(x=Y,breaks=br,right=F,include.lowest=T,labels=lab)

Thursday 21st August 2025.

#Exercise 4.4
#(#Solution
#(a)
#cat("\"The quick brown fox \n\tjumped over\n\t\tthe lazy dogs\"")

#(b)
#Returning a written values with objects registered on R
num1<-4
num2<-0.75
paste("The result of multiplying",num1,"by",num2,"is",num1*num2)
## [1] "The result of multiplying 4 by 0.75 is 3"
#(c)
Path<-("C:/Users/hp/OneDrive/Documents/ICAMMDA/3rd Week of my IT/")
gsub("hp","JAlushi",Path)
## [1] "C:/Users/JAlushi/OneDrive/Documents/ICAMMDA/3rd Week of my IT/"
#Substituting "hp"

#(d)
#i.
bar<-"How much wood could a woodchucks chuck"
substr(bar,1,nchar(bar))<-"if a woodchuck could chuck wood"
bar
## [1] "if a woodchuck could chuck woods chuck"
#ii.
gsub("wood","metal",bar)
## [1] "if a metalchuck could chuck metals chuck"
#(e)
Storestr<-"Two 6-packs for $12.99"
#i.
substr(Storestr,5,10)
## [1] "6-pack"
#ii.
gsub("12.99","10.99",Storestr)
## [1] "Two 6-packs for $10.99"

Friday 22nd August 2025.

#Chapter 5
#An Introduction to the List and Data Frame
#foo<-list(matrix(data=1:4,nrow=2,ncol=2),c(T,F,T,T),"hello","Mark Abdul")
#foo

#Checking the numbers of object in a list using the "length" function.
#length(foo)


#Exercise 4.5
#Solutions
Pol.party<-c("National","Labour","Greens","Maori","Other")
A<-(1:20)
num.females<-c(1,5:7,12,14:16)
num.males<-A[-(num.females)]
Labour<-c(1,4,12,15,16,19)
Maori<-c()
Greens<-c(6,9,11)
Other<-c(10,20)
National<-c(2,3,5,7,8,13,14,17,18)

A[Labour]<-"Labour"
A[Greens]<-"Greens"
A[Other]<-"Other"
A[National]<-"National"
A
##  [1] "Labour"   "National" "National" "Labour"   "National" "Greens"  
##  [7] "National" "National" "Greens"   "Other"    "Greens"   "Labour"  
## [13] "National" "National" "Labour"   "Labour"   "National" "National"
## [19] "Labour"   "Other"
#(a)
sex<-rep("M",20)
sex[num.females]<-"F"
sex
##  [1] "F" "M" "M" "M" "F" "F" "F" "M" "M" "M" "M" "F" "M" "F" "F" "F" "M" "M" "M"
## [20] "M"
party<-A

#(b)
sex.factor<-factor(x=sex,ordered=TRUE)
sex.factor
##  [1] F M M M F F F M M M M F M F F F M M M M
## Levels: F < M
party.factor<-factor(x=party,ordered=TRUE)
party.factor
##  [1] Labour   National National Labour   National Greens   National National
##  [9] Greens   Other    Greens   Labour   National National Labour   Labour  
## [17] National National Labour   Other   
## Levels: Greens < Labour < National < Other
#Yes because R tends to arrange the Levels by specifying which one is less than the other.

#(c)
#i.
party.factor[(sex.factor=="F")]
## [1] Labour   National Greens   National Labour   National Labour   Labour  
## Levels: Greens < Labour < National < Other
#ii.
sex.factor[party.factor=="National"]
## [1] M M F F M M F M M
## Levels: F < M
#(d)
#i.
new.party_factor<-c(party.factor,c("National","Maori","Maori","Labour","Greens","Labour"))
new.party_factor
##  [1] "2"        "3"        "3"        "2"        "3"        "1"       
##  [7] "3"        "3"        "1"        "4"        "1"        "2"       
## [13] "3"        "3"        "2"        "2"        "3"        "3"       
## [19] "2"        "4"        "National" "Maori"    "Maori"    "Labour"  
## [25] "Greens"   "Labour"
new.sex_factor<-c(sex.factor,c("M","M","F","F","F","M"))
new.sex_factor
##  [1] "1" "2" "2" "2" "1" "1" "1" "2" "2" "2" "2" "1" "2" "1" "1" "1" "2" "2" "2"
## [20] "2" "M" "M" "F" "F" "F" "M"
#ii.
result<-c(93,55,29,100,52,84,56,0,33,52,35,53,55,46,40,40,56,45,64,31,10,29,40,95,18,61)

#(e)
br<-c(0,30,70,100)
lab<-c("Low","Moderate","High")
B<-cut(x=result,breaks = br,right = FALSE,include.lowest = TRUE,labels =lab )

#(f)
B[new.party_factor=="Labour"]
## [1] High     Moderate
## Levels: Low Moderate High
B[new.party_factor=="National"]
## [1] Low
## Levels: Low Moderate High
#I noticed that after extraction Labour party tends to have (High and Moderate) confidence level but on the other hand National party yielded only Low confidence level.

Week 5

ICMSO Conference.

Week 6

Monday 1st September 2025.

#Retrieving components from a list using the known Indexes format,but now  now entered in double bracket.
#Recall that we used the following:
  foo<-list(matrix(1:4,2,2),c(T,F,T,T),"hello")
foo
## [[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## [[2]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## [[3]]
## [1] "hello"
#Extraction
foo[[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
foo[[3]]
## [1] "hello"
#Member referencing
foo[[1]]+5.5
##      [,1] [,2]
## [1,]  6.5  8.5
## [2,]  7.5  9.5
#Extracting the first and second (row and column) of a  matrix
foo[[1]][1,2]
## [1] 3
foo[[1]][2,]
## [1] 2 4
#Adding a set of character values.
cat(foo[[3]],"you!")
## hello you!
foo[[3]]
## [1] "hello"
foo[[3]]<-paste(foo[[3]],"you!")
foo
## [[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## [[2]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## [[3]]
## [1] "hello you!"
#Accessing some components of foo (Accessing the 2 and 3 components of foo)
foo[[c(2,3)]]
## [1] 8
#List slicing (We use only a single square bracket)
bar<-foo[c(2,3)]
bar
## [[1]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## [[2]]
## [1] "hello you!"
#This results to the 2 and 3rd component in the list environs
#Note: the "bar" also denotes a new list with two components.


#5.1.2 Naming of components in a list
names(foo)<-c("mymatrix","mylogicals","mystring")
foo
## $mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $mystring
## [1] "hello you!"
baz<-list(array(1:20,c(2,2,5)),"Amina is coming tomorrow",c(T,F,F,F,T),"Andrews")
baz
## [[1]]
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## [[2]]
## [1] "Amina is coming tomorrow"
## 
## [[3]]
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## [[4]]
## [1] "Andrews"
names(baz)<-c("Numeric array","Wife","Logicals","Husband")
baz
## $`Numeric array`
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## $Wife
## [1] "Amina is coming tomorrow"
## 
## $Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## $Husband
## [1] "Andrews"
#Extraction with specific names
baz$Husband
## [1] "Andrews"
baz$Wife
## [1] "Amina is coming tomorrow"
baz$Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
#More on extraction
foo[[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
#more on extraction
foo[[1]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
baz[[1]]
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
#Sub-setting named members also works the same way
all(baz$"Numerical array"[,2,]==baz[[1]][,2,])
## [1] TRUE
#The above code show me that the comparison is TRUE.

#Assigning a label to each component
bar<-list(tom=c(foo[[2]],T,T,T,F),dick="g'day mate",harry=foo$mymatrix*2)
bar
## $tom
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8  3  4  8  3  4  8  3  4  8  3
## [26] -1  1 -3  1  5
## 
## $dick
## [1] "g'day mate"
## 
## $harry
##      [,1] [,2]
## [1,]    2    6
## [2,]    4    8
#To check the objects name using the "names" function
names(bar)
## [1] "tom"   "dick"  "harry"
#When using the names function, the component names are always provided and
#(returned as character strings in double quotes. However, if you’re specifying names
#when a list is created (inside the list function) or using names to extract members
#with the dollar operator, the names are entered without quotes (in other words, they
#                                                                are not given as strings)

Tuesday 2nd September 2025.

#Nesting:
  baz$bobby<-foo
baz
## $`Numeric array`
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## $Wife
## [1] "Amina is coming tomorrow"
## 
## $Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## $Husband
## [1] "Andrews"
## 
## $bobby
## $bobby$mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $bobby$mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $bobby$mystring
## [1] "hello you!"
foo$bobby<-baz
foo
## $mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $mystring
## [1] "hello you!"
## 
## $bobby
## $bobby$`Numeric array`
## , , 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 3
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 4
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16
## 
## , , 5
## 
##      [,1] [,2]
## [1,]   17   19
## [2,]   18   20
## 
## 
## $bobby$Wife
## [1] "Amina is coming tomorrow"
## 
## $bobby$Logicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
## 
## $bobby$Husband
## [1] "Andrews"
## 
## $bobby$bobby
## $bobby$bobby$mymatrix
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $bobby$bobby$mylogicals
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $bobby$bobby$mystring
## [1] "hello you!"
baz$bobby$mylogicals[1:3]
## [1] 3 4 8
#More
baz[[5]][[2]][1:3]
## [1] 3 4 8
baz[[5]]$mylogicals[1:3]
## [1] 3 4 8
#Requesting for the first three elements of the component of a list.

Wednesday 3rd September 2025.

#Exercise 5.1
#(a)
a<-seq(-4,4,length.out=20)
b<-matrix(c(F,T,T,T,F,T,T,F,F),3,3)
## Warning in matrix(c(F, T, T, T, F, T, T, F, F), 3, 3): data length differs from
## size of matrix: [39 != 3 x 3]
c<-c("don","quixote")
d<-factor(c("LOW","MED","LOW","MED","MED","HIGH"))

#Creating a list
var<-list(seq(-4,4,length.out=20),matrix(c(F,T,T,T,F,T,T,F,F),3,3),c("don","quixote"),factor(c("LOW","MED","LOW","MED","MED","HIGH")))
## Warning in matrix(c(F, T, T, T, F, T, T, F, F), 3, 3): data length differs from
## size of matrix: [39 != 3 x 3]
names(var)<-c("Numericals","Logical matrix","String character","factor")

#Extracting
#(i)
var$`Logical matrix`[c(2,1),c(2,3)]
##      [,1] [,2]
## [1,]    1    4
## [2,]   -3    3
cat(var$`String character`)
## don quixote
#(ii)
M<-sub(pattern="quixote",replacement = "Quixote",x=var)
M
## [1] "c(-4, -3.57894736842105, -3.15789473684211, -2.73684210526316, -2.31578947368421, -1.89473684210526, -1.47368421052632, -1.05263157894737, -0.631578947368421, -0.210526315789474, 0.210526315789473, 0.631578947368421, 1.05263157894737, 1.47368421052632, 1.89473684210526, 2.31578947368421, 2.73684210526316, 3.1578947368421, 3.57894736842105, 4)"
## [2] "c(3, -1, 1, -3, 1, 5, 3, 4, 8)"                                                                                                                                                                                                                                                                                                                          
## [3] "c(\"don\", \"Quixote\")"                                                                                                                                                                                                                                                                                                                                 
## [4] "c(2, 3, 2, 3, 3, 1)"
M<-sub(pattern="don",replacement = "Don",x=M)
M
## [1] "c(-4, -3.57894736842105, -3.15789473684211, -2.73684210526316, -2.31578947368421, -1.89473684210526, -1.47368421052632, -1.05263157894737, -0.631578947368421, -0.210526315789474, 0.210526315789473, 0.631578947368421, 1.05263157894737, 1.47368421052632, 1.89473684210526, 2.31578947368421, 2.73684210526316, 3.1578947368421, 3.57894736842105, 4)"
## [2] "c(3, -1, 1, -3, 1, 5, 3, 4, 8)"                                                                                                                                                                                                                                                                                                                          
## [3] "c(\"Don\", \"Quixote\")"                                                                                                                                                                                                                                                                                                                                 
## [4] "c(2, 3, 2, 3, 3, 1)"
M$`String character`<-M[[3]]
## Warning in M$`String character` <- M[[3]]: Coercing LHS to a list
var
## $Numericals
##  [1] -4.0000000 -3.5789474 -3.1578947 -2.7368421 -2.3157895 -1.8947368
##  [7] -1.4736842 -1.0526316 -0.6315789 -0.2105263  0.2105263  0.6315789
## [13]  1.0526316  1.4736842  1.8947368  2.3157895  2.7368421  3.1578947
## [19]  3.5789474  4.0000000
## 
## $`Logical matrix`
##      [,1] [,2] [,3]
## [1,]    3   -3    3
## [2,]   -1    1    4
## [3,]    1    5    8
## 
## $`String character`
## [1] "don"     "quixote"
## 
## $factor
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
d<-M[[3]]
d
## [1] "c(\"Don\", \"Quixote\")"
d <- "Don Quixote"

cat("Windmills! ATTACK!", "\n\t-\\",d,"/-\n")
## Windmills! ATTACK! 
##  -\ Don Quixote /-
#(iii)
var$Numericals[var$Numericals>1]
## [1] 1.052632 1.473684 1.894737 2.315789 2.736842 3.157895 3.578947 4.000000
#(iv)
which(var$factor=="MED")
## [1] 2 4 5
#(b)
bar<-list(var$factor,c(3,2.1,3.3,4,1.5,4.9),var[(1:3)])
names(bar)<-c("facs","nums","oldlist")
bar
## $facs
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
## 
## $nums
## [1] 3.0 2.1 3.3 4.0 1.5 4.9
## 
## $oldlist
## $oldlist$Numericals
##  [1] -4.0000000 -3.5789474 -3.1578947 -2.7368421 -2.3157895 -1.8947368
##  [7] -1.4736842 -1.0526316 -0.6315789 -0.2105263  0.2105263  0.6315789
## [13]  1.0526316  1.4736842  1.8947368  2.3157895  2.7368421  3.1578947
## [19]  3.5789474  4.0000000
## 
## $oldlist$`Logical matrix`
##      [,1] [,2] [,3]
## [1,]    3   -3    3
## [2,]   -1    1    4
## [3,]    1    5    8
## 
## $oldlist$`String character`
## [1] "don"     "quixote"
#(i)
bar$facs[bar$nums>=3]
## [1] LOW  LOW  MED  HIGH
## Levels: HIGH LOW MED
#(ii)
bar$flags<-rep(bar$oldlist$`Logical matrix`[,3],2)
bar$flags
## [1] 3 4 8 3 4 8
#(iii)
bar$nums[!bar$flags]
## numeric(0)
#(iv)
bar$oldlist$`String character`<-"Don Quixote"
R<-cat(bar$oldlist$`String character`)
## Don Quixote
bar
## $facs
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
## 
## $nums
## [1] 3.0 2.1 3.3 4.0 1.5 4.9
## 
## $oldlist
## $oldlist$Numericals
##  [1] -4.0000000 -3.5789474 -3.1578947 -2.7368421 -2.3157895 -1.8947368
##  [7] -1.4736842 -1.0526316 -0.6315789 -0.2105263  0.2105263  0.6315789
## [13]  1.0526316  1.4736842  1.8947368  2.3157895  2.7368421  3.1578947
## [19]  3.5789474  4.0000000
## 
## $oldlist$`Logical matrix`
##      [,1] [,2] [,3]
## [1,]    3   -3    3
## [2,]   -1    1    4
## [3,]    1    5    8
## 
## $oldlist$`String character`
## [1] "Don Quixote"
## 
## 
## $flags
## [1] 3 4 8 3 4 8

Thursday 4th September 2025.

Review Class.

2+3
## [1] 5
sqrt(9)
## [1] 3
2*5
## [1] 10
((0.44*(1-0.44))/34)^(1/2)
## [1] 0.08512966
log(225,15)
## [1] 2
#Solving a particular problem.
a=2.3
(6*a+42)/(3^(4.2-3.62))
## [1] 29.50556
#Another problem
(-4)^2+2
## [1] 18
-4^2+2
## [1] -14
(-4)^(2+2)
## [1] 256
-4^(2+2)
## [1] -256
log(3,exp(1))
## [1] 1.098612
#Assignment
x=10
mynumber=45.5
y=mynumber*x
y
## [1] 455
#Create an object that stores the value 32 418.
#b. Overwrite your object in (a) by itself divided by 2.33. Print the
#result to the console.
#c.
#Create a new object with the value 82 10 13.
#d. Print directly to the console the result of multiplying (b) by (c).

#(a)
vicka<-3^2*(4^(1/8))
vicka
## [1] 10.70286
#(b)
vicka<-vicka/2.33   #Overwriting
vicka
## [1] 4.593504
#(c)
vicka1<--8.2*10^(-13)
vicka1
## [1] -8.2e-13
#(d)
vicka*vicka1
## [1] -3.766673e-12

Friday 5th September 2025.

mydata<-data.frame(person=c("Peter","Lois","Meg","Chris","Stewie"),
                   age=c(42,40,17,14,1),
                   sex=factor(c("M","F","F","M","M")))
mydata
##   person age sex
## 1  Peter  42   M
## 2   Lois  40   F
## 3    Meg  17   F
## 4  Chris  14   M
## 5 Stewie   1   M
#Extracting portion of data
mydata[2,2]
## [1] 40
mydata[3:5,3]
## [1] F M M
## Levels: F M
#Extraction in a certain order
mydata[,c(3,1)]
##   sex person
## 1   M  Peter
## 2   F   Lois
## 3   F    Meg
## 4   M  Chris
## 5   M Stewie
#using the dollar sign to extract a member of the object passed to data.frame.
mydata$age
## [1] 42 40 17 14  1
#Sub-setting this returned vector too, we do:
mydata$age[2]
## [1] 40
#In data-frame column stands for "variables" and the row stands for "Records".

#Reporting the size of a data-frame.
nrow(mydata)
## [1] 5
ncol(mydata)
## [1] 3
dim(mydata)
## [1] 5 3
#R default set character variables to vector as thus:
mydata$person
## [1] "Peter"  "Lois"   "Meg"    "Chris"  "Stewie"
#Adding Data Columns and Combining Data Frames.
newrecord<-data.frame(person="Brain",age=7,
  sex=factor("M",levels = levels(mydata$sex)))

newrecord
##   person age sex
## 1  Brain   7   M
#Now I can put the new record into the old data frame record list.
mydata<-rbind(mydata,newrecord)
mydata
##   person age sex
## 1  Peter  42   M
## 2   Lois  40   F
## 3    Meg  17   F
## 4  Chris  14   M
## 5 Stewie   1   M
## 6  Brain   7   M
#Adding a column (Variable)
funny<-c("High","High","Low","Med","High","Med")
funny<-factor(funny,levels=c("Low","Med","High"))
funny
## [1] High High Low  Med  High Med 
## Levels: Low Med High
#Now add the column that is (variables)
mydata<-cbind(mydata,funny)
mydata
##   person age sex funny
## 1  Peter  42   M  High
## 2   Lois  40   F  High
## 3    Meg  17   F   Low
## 4  Chris  14   M   Med
## 5 Stewie   1   M  High
## 6  Brain   7   M   Med
#Adding a new colum with the dollar sign
mydata$age.mom<-mydata$age*12
mydata
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 2   Lois  40   F  High     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
## 6  Brain   7   M   Med      84
#Logical Record Subset
#Examining all records corresponding to males ~ "mydata"
mydata$sex=="M"  #Identifying relevant position
## [1]  TRUE FALSE FALSE  TRUE  TRUE  TRUE
#Now getting all the record that pertain the data.frame
mydata[mydata$sex=="M",]
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
## 6  Brain   7   M   Med      84
#Removing a certain column (variable)
mydata[mydata$sex=="M",-3]
##   person age funny age.mom
## 1  Peter  42  High     504
## 4  Chris  14   Med     168
## 5 Stewie   1  High      12
## 6  Brain   7   Med      84
#Now If I want to extract certain variables with conditions.
mydata[mydata$sex=="M",c("person","age","funny","age.mom")]
##   person age funny age.mom
## 1  Peter  42  High     504
## 4  Chris  14   Med     168
## 5 Stewie   1  High      12
## 6  Brain   7   Med      84
#Extracting the full records for individuals who are more than 10years old OR have a high degree of funniness
mydata[mydata$age>10|mydata$funny=="High",]
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 2   Lois  40   F  High     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
#Check this out:
mydata[mydata$age<45,] #but with
##   person age sex funny age.mom
## 1  Peter  42   M  High     504
## 2   Lois  40   F  High     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      12
## 6  Brain   7   M   Med      84
mydata[mydata$age>45,] #Yields an empty result
## [1] person  age     sex     funny   age.mom
## <0 rows> (or 0-length row.names)

Week 7

Monday 8th september 2025.

#Exercise 5.2
#(a)
#Creating and storing some set of data as dframe in my workspace.
dframe<-data.frame(person=c("Stan","Francine","Steve","Roger","Hayley","Klaus"),
                   sex=factor(c("M","F","M","M","F","M"),levels=c("F","M")),
                   funny=factor(c("High","Med","Low","High","Med","Med"),
                    levels=c("Low","Med","High")))
dframe
##     person sex funny
## 1     Stan   M  High
## 2 Francine   F   Med
## 3    Steve   M   Low
## 4    Roger   M  High
## 5   Hayley   F   Med
## 6    Klaus   M   Med
#(b)
dframe$age<-c(41,41,15,1600,21,60)
dframe
##     person sex funny  age
## 1     Stan   M  High   41
## 2 Francine   F   Med   41
## 3    Steve   M   Low   15
## 4    Roger   M  High 1600
## 5   Hayley   F   Med   21
## 6    Klaus   M   Med   60
#(c)
dframe<-data.frame(dframe$person,dframe$age,dframe$sex,dframe$funny)
dframe
##   dframe.person dframe.age dframe.sex dframe.funny
## 1          Stan         41          M         High
## 2      Francine         41          F          Med
## 3         Steve         15          M          Low
## 4         Roger       1600          M         High
## 5        Hayley         21          F          Med
## 6         Klaus         60          M          Med
names(dframe)<-c("person","age","sex","funny")
dframe
##     person  age sex funny
## 1     Stan   41   M  High
## 2 Francine   41   F   Med
## 3    Steve   15   M   Low
## 4    Roger 1600   M  High
## 5   Hayley   21   F   Med
## 6    Klaus   60   M   Med
#OR
dframe<-data.frame(dframe[,c(1,4,2,3)])
dframe
##     person funny  age sex
## 1     Stan  High   41   M
## 2 Francine   Med   41   F
## 3    Steve   Low   15   M
## 4    Roger  High 1600   M
## 5   Hayley   Med   21   F
## 6    Klaus   Med   60   M
#(d)
#Noting that mydata is saved already

mydata2<-mydata[,-5]
mydata2
##   person age sex funny
## 1  Peter  42   M  High
## 2   Lois  40   F  High
## 3    Meg  17   F   Low
## 4  Chris  14   M   Med
## 5 Stewie   1   M  High
## 6  Brain   7   M   Med
#(e)
mydataframe<-rbind(mydata2,dframe)
mydataframe
##      person  age sex funny
## 1     Peter   42   M  High
## 2      Lois   40   F  High
## 3       Meg   17   F   Low
## 4     Chris   14   M   Med
## 5    Stewie    1   M  High
## 6     Brain    7   M   Med
## 7      Stan   41   M  High
## 8  Francine   41   F   Med
## 9     Steve   15   M   Low
## 10    Roger 1600   M  High
## 11   Hayley   21   F   Med
## 12    Klaus   60   M   Med
#(f)
#mydataframe$person&mydataframe$age[(mydataframe$funny)=="Med"|(mydataframe$funny)=="High"]
#mydataframe

# f
subset(mydataframe, sex == "F" & (funny == "Med" | funny == "High"),
       select = c(person, age))
##      person age
## 2      Lois  40
## 8  Francine  41
## 11   Hayley  21
#(g)

subset(mydataframe, substr(person, 1, 1) == "S")
##   person age sex funny
## 5 Stewie   1   M  High
## 7   Stan  41   M  High
## 9  Steve  15   M   Low
#Note:
  #substr(x,start,stop)
#subset(x,subset,select)

#*Note that this are #bases*.

#list of important symbols #for extraction:

#[[ ]],
#[ ],
# $,
 #[ , ].

Tuesday 9th September 2025.

#Creating some objects to test out the special value "Inf".
foo<-Inf
foo
## [1] Inf
bar<-c(3401,Inf,3.1,-555,Inf,43)
bar
## [1] 3401.0    Inf    3.1 -555.0    Inf   43.0
baz<-90000^100
baz
## [1] Inf
#R can also represent negative infinite numbers.
qux<-c(-42,565,-Inf,-Inf,Inf,-45632.3)
qux
## [1]    -42.0    565.0     -Inf     -Inf      Inf -45632.3
#Multiplication with infinity
Inf*-9
## [1] -Inf
#it's result in a negative number because any negative value multiplied by infinity results to negative Inf'

#Other operations with the special value infinity.
Inf+1
## [1] Inf
4*-Inf
## [1] -Inf
-45.2-Inf
## [1] -Inf
Inf-45.2
## [1] Inf
Inf+Inf
## [1] Inf
Inf/23
## [1] Inf
#Zero and infinity goes hand in hand as thus:
-59/Inf
## [1] 0
-59/-Inf
## [1] 0
#Though this is not mathematically correct.Any nonzero value divide by infinity result in infinity.
-59/0
## [1] -Inf
59/0
## [1] Inf
Inf/0
## [1] Inf
#Detecting infinite and finite values in a data structure with "is.finite and is.infinite" functions!
qux
## [1]    -42.0    565.0     -Inf     -Inf      Inf -45632.3
is.infinite(qux)
## [1] FALSE FALSE  TRUE  TRUE  TRUE FALSE
is.finite(qux)
## [1]  TRUE  TRUE FALSE FALSE FALSE  TRUE
#Note that the function "is.finite" is the negation of "is.infinite".

#Relational operator on the special value Inf.
-Inf<Inf
## [1] TRUE
Inf>Inf
## [1] FALSE
qux==Inf
## [1] FALSE FALSE FALSE FALSE  TRUE FALSE
qux==-Inf
## [1] FALSE FALSE  TRUE  TRUE FALSE FALSE
# The special value NaN (Not a number)
foo<-NaN
foo
## [1] NaN
bar<-c(NaN,54.3,-2,NaN,90094.12,-Inf,55)
bar
## [1]      NaN    54.30    -2.00      NaN 90094.12     -Inf    55.00
#This example is strictly on when I don't want to see the value of the Inf!
-Inf+Inf
## [1] NaN
Inf/Inf
## [1] NaN
#NaN results when 0 divides 0.
0/0
## [1] NaN
#Note that any mathematical operation involving NaN results in NaN!
NaN+1
## [1] NaN
2+6*(4-4)/0
## [1] NaN
3.5^(-Inf/Inf)
## [1] NaN
#More
bar
## [1]      NaN    54.30    -2.00      NaN 90094.12     -Inf    55.00
is.nan(bar)
## [1]  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE
!is.nan(bar)
## [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
is.nan(bar)|is.infinite(bar)
## [1]  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE
a<-is.nan(bar)|is.infinite(bar)

#Extraction with "is.nan"
bar[-a]
## [1]    54.30    -2.00      NaN 90094.12     -Inf    55.00
bar[-(which(is.nan(bar)|is.infinite(bar)))]
## [1]    54.30    -2.00 90094.12    55.00

Wednesday 10th September 2025.

#Exercise 6.1
#Solution.
#(a)
foo<-c(13563,-14156,-14319,16981,12921,11979,9568,8833,-12968,8133)

#(i) #Outputting those values of foo that when raised to the power of 75 would be infinity.
foo[!is.finite(foo^(75))]
## [1]  13563 -14156 -14319  16981  12921 -12968
#(ii)
foo[-(foo^(75)==-Inf)]
## [1] -14156 -14319  16981  12921  11979   9568   8833 -12968   8133
#Returning the elements of foo that when raise to the power of 75 does not return negative Inf.

#(b)
bar<-matrix(c(77875.40,-35466.25,-39803.81,27551.45,-7333.85,55976.34,2376.30,36599.69,76694.82,-36478.88,-70585.69,47032.00),3,4)
bar
##           [,1]     [,2]     [,3]      [,4]
## [1,]  77875.40 27551.45  2376.30 -36478.88
## [2,] -35466.25 -7333.85 36599.69 -70585.69
## [3,] -39803.81 55976.34 76694.82  47032.00
#(i)
which(is.nan(bar^65/Inf))
## [1]  1  6  9 11
#Identifying the coordinate specific indexes of the entries in bar.

#(ii)
#Returning those values that are in bar that are not NaN.
which(!is.nan(bar^67+Inf))
##  [1]  1  2  3  4  5  6  7  8  9 10 12
A<-which(!is.nan(bar^67+Inf))

#Confirmation
A==which(bar^67!=-Inf)
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#(iii)
bar[(bar^67 == -Inf) | is.finite(bar^67)]
## [1] -35466.25 -39803.81  27551.45  -7333.85   2376.30  36599.69 -36478.88
## [8] -70585.69

Thursday 11th September 2025.

#Na
#Examples of NA values (Not available)
#For character vector type
foo<-c("character","a",NA,"with","string",NA)
foo
## [1] "character" "a"         NA          "with"      "string"    NA
#for factor vector data type
bar<-factor(c("blue",NA,NA,"blue","green",NA,"red","red",NA,"green"))
bar
##  [1] blue  <NA>  <NA>  blue  green <NA>  red   red   <NA>  green
## Levels: blue green red
#for numeric vector
baz<-matrix(c(1:3,NA,5,6,NA,8,NA),3,3)
baz
##      [,1] [,2] [,3]
## [1,]    1   NA   NA
## [2,]    2    5    8
## [3,]    3    6   NA
#Identifying and eliminating the Not available values in an object.
qux<-c(NA,5.89,Inf,NA,9.43,-2.35,NaN,2.10,-8.53,-7.58,NA,-4.58,2.01,NaN)
qux
##  [1]    NA  5.89   Inf    NA  9.43 -2.35   NaN  2.10 -8.53 -7.58    NA -4.58
## [13]  2.01   NaN
#Checking foe NA
is.na(qux)
##  [1]  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
## [13] FALSE  TRUE
#Separating between the NA and NaN when extracted this values in the same vector environs.
which(is.nan(qux))  #This is to only identify NaN values.
## [1]  7 14
#Identifying only the NA values!
which(is.na(qux)&!is.nan(qux))
## [1]  1  4 11
#Deleting all NAs values in a vector with "na.omit"
quux<-na.omit(qux)
quux
## [1]  5.89   Inf  9.43 -2.35  2.10 -8.53 -7.58 -4.58  2.01
## attr(,"na.action")
## [1]  1  4  7 11 14
## attr(,"class")
## [1] "omit"
#Performing arithmetic operation with NA and NaN.
3+2.1*NA-4
## [1] NA
3*c(1,2,NA,NA,NaN,6)
## [1]   3   6  NA  NA NaN  18
76>NaN
## [1] NA
#NULL value
foo<-NULL
foo
## NULL
bar<-NA
bar
## [1] NA
#Vectorized NULL, noting that NULL is a value that represents an empty element.
c(2,4,NA,8)
## [1]  2  4 NA  8
c(2,4,NULL,8)
## [1] 2 4 8
#Null Another explicit example
c(NA,NA,NA)  #Unrecorded observation
## [1] NA NA NA
c(NULL,NULL,NULL)  #Emptiness three times
## NULL
#Using the is.null function to extract the facts that the vector is actually NULL or not.
opt.arg<-c("string1","string2","string3")

#Checking whether the argument supplied using NA
is.na(opt.arg)
## [1] FALSE FALSE FALSE
#'is.na' operates element wise and that means there would be values present in the output that might be problematic.
is.null(opt.arg)
## [1] FALSE
#Checking again for na,and null flags
opt.arg<-c(NA,NA,NA)
is.na(opt.arg)
## [1] TRUE TRUE TRUE
opt.arg<-c(NULL,NULL,NULL)
is.null(opt.arg)
## [1] TRUE
#Some little operation with NULL
NULL+53
## numeric(0)
53<=NULL
## logical(0)
#With some special symbols
NaN-NULL+NA/Inf
## numeric(0)
#Examining List and dataframe
foo<-list(member1=c(33,1,5.2,7),member2="NA or NULL?")
foo
## $member1
## [1] 33.0  1.0  5.2  7.0
## 
## $member2
## [1] "NA or NULL?"
#Accessing a member in foo
foo$member3  #Result into NULL
## NULL
#Filling an empty member with a value
foo$member3<-NA
foo
## $member1
## [1] 33.0  1.0  5.2  7.0
## 
## $member2
## [1] "NA or NULL?"
## 
## $member3
## [1] NA

Friday 12th September 2025.

#Exercise 6.2
#(a)
foo<-c(4.3,2.2,NULL,2.4,NaN,3.3,3.1,NULL,3.4,NA)
foo
## [1] 4.3 2.2 2.4 NaN 3.3 3.1 3.4  NA
#(i)
length(foo)
## [1] 8
#(ii)
which(is.na(foo))
## [1] 4 8
#(iii)
is.null(foo)
## [1] FALSE
#(iv)
is.na(foo[8])+4/NULL
## numeric(0)
#(b)
A<-list(c(7,7,NA,3,NA,1,1,5,NA))

#(i)
names(A)<-"alpha"

#(ii)
A$beta
## NULL
#(iii)
A$beta<-which(is.na(A$alpha))
A
## $alpha
## [1]  7  7 NA  3 NA  1  1  5 NA
## 
## $beta
## [1] 3 5 9
#ggplot2 class
library(ggplot2)

#Using ggplot2 package

foo<-c(1.1,2,3.5,3.9,4.2)
bar<-c(2,2.2,-1.3,0,0.2)

qplot(foo,bar)

qplot(foo,bar,main="My Lovely qplot",xlab = "X axis Label",ylab="Location y")

qplot(foo,bar,main="My Lovely qplot",xlab = "X axis Label",ylab="Location y")+
  geom_line(type="n",lty=7,col="red",lwd=2)
## Warning in geom_line(type = "n", lty = 7, col = "red", lwd = 2): Ignoring
## unknown parameters: `type`

Week 8

Monday 15th September 2025.

6.2 Understanding Types, Classes, and Coercion

Atributes
Consider the following example with an attribute function :
   foo<-matrix(data=1:9,nrow=3,ncol=3)
foo   
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
Now applying the attribute function
attributes(foo)
## $dim
## [1] 3 3
Calling or to find the attribute the content of dim.
attributes(foo)$dim
## [1] 3 3
For the dimension of a matrix we’ve already that dim(x) produces the dimensions of vector matrix “X”
dim(foo)
## [1] 3 3

Tuesday 16th September 2025.

Creating a matrix and attributing names to the row and column of the matrix using the “dimnames” function.
bar<-matrix(1:9,3,3,dimnames = list(c("A","B","C"),c("D","E","F")))
bar
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9
Note that if you didn’t attribute “dimnames” to the matrix as an optional function if you call it, it’ll only return NULL result.
attributes(bar)
## $dim
## [1] 3 3
## 
## $dimnames
## $dimnames[[1]]
## [1] "A" "B" "C"
## 
## $dimnames[[2]]
## [1] "D" "E" "F"
Modifying some attributes using attribute-specific function.
dimnames(foo)<-list(c("A","B","C"),c("D","E","F"))
foo
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9
Stand-alone Vectors: Note that stand alone vectors does not have anything to do with attributes.

E.g

num.vec1<-1:4
num.vec1
## [1] 1 2 3 4
num.vec2<-seq(1,4,len=6)
num.vec2
## [1] 1.0 1.6 2.2 2.8 3.4 4.0
char.vec<-c("a","few","strings","here")
char.vec
## [1] "a"       "few"     "strings" "here"
logic.vec<-c(T,F,F,F,T,F,T,T)
logic.vec
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8  3
## [26] -1  1 -3  1  5  3  4  8  3  4  8
fac.vec<-factor(c("Blue","Blue","Green","Red","Green","Yellow"))
fac.vec
## [1] Blue   Blue   Green  Red    Green  Yellow
## Levels: Blue Green Red Yellow
Checking the classes of Objects stored in R with the “class” function.
class(num.vec1)
## [1] "integer"
class(num.vec2)
## [1] "numeric"
class(char.vec)
## [1] "character"
class(logic.vec)
## [1] "numeric"
class(fac.vec)
## [1] "factor"
class(foo)
## [1] "matrix" "array"
class(bar)
## [1] "matrix" "array"
Checking for the structure of the date stored in and object in R with the function “class”.
num.mat1<-matrix(num.vec1,2,2)
num.mat1
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
num.mat2<-matrix(num.vec2,2,3)
num.mat2
##      [,1] [,2] [,3]
## [1,]  1.0  2.2  3.4
## [2,]  1.6  2.8  4.0
char.mat<-matrix(char.vec,2,2)
char.mat
##      [,1]  [,2]     
## [1,] "a"   "strings"
## [2,] "few" "here"
logic.mat<-matrix(logic.vec,4,2)
## Warning in matrix(logic.vec, 4, 2): data length differs from size of matrix:
## [36 != 4 x 2]
logic.mat
##      [,1] [,2]
## [1,]    3   -1
## [2,]    4    1
## [3,]    8   -3
## [4,]    3    1
fac.mat<-matrix(fac.vec,2,3) #Note that factors are only used in vector form.
fac.mat
##      [,1]   [,2]    [,3]    
## [1,] "Blue" "Green" "Green" 
## [2,] "Blue" "Red"   "Yellow"
Check the matrix with “class” function.
class(num.mat1)
## [1] "matrix" "array"
class(num.mat2)
## [1] "matrix" "array"
class(char.mat)
## [1] "matrix" "array"
class(logic.mat)
## [1] "matrix" "array"
class(fac.mat) #Not associated with c;lass!
## [1] "matrix" "array"
Multiple Classes
ordfac.vec<-factor(c("Small","Large","Large","Regular","Small"),
                   levels=c("Small","Regular","Large"),
                   ordered=TRUE)
ordfac.vec
## [1] Small   Large   Large   Regular Small  
## Levels: Small < Regular < Large
Checking the class:
class(ordfac.vec)
## [1] "ordered" "factor"
is-Dot function can check for any class name!
num.vec1<-1:4
num.vec1
## [1] 1 2 3 4
is.integer(num.vec1)
## [1] TRUE
is.numeric((num.vec1))
## [1] TRUE
is.matrix(num.vec1)
## [1] FALSE
is.data.frame(num.vec1)
## [1] FALSE
is.vector(num.vec1)
## [1] TRUE
is.logical(num.vec1)
## [1] FALSE
As-Dot Coercion functions:Implicit Coercion, converting

logical values to thier numeric counterparts.

1:4+c(T,F,F,T)
## Warning in 1:4 + c(T, F, F, T): longer object length is not a multiple of
## shorter object length
##  [1]  4  6 11  7  0  3  0  5  6  5  2  5 -2  3  8  7  5 10
Note this the results are given in the context of numerical values given that F=0 and T=1
Using the Cat and Paste function to glue and coerce some values.
foo<-34
bar<-T

paste("Definitely foo: ",foo,"; definitely bar: ",bar,".",sep="")
## [1] "Definitely foo: 34; definitely bar: 3."
## [2] "Definitely foo: 34; definitely bar: 4."
## [3] "Definitely foo: 34; definitely bar: 8."
Other example of coercion
as.numeric(c(T,F,F,T))
##  [1]  3  4  8  3 -1  1 -3  1  5  3 -1  1 -3  1  5  3  4  8
1:4+as.numeric(c(T,F,F,T))
## Warning in 1:4 + as.numeric(c(T, F, F, T)): longer object length is not a
## multiple of shorter object length
##  [1]  4  6 11  7  0  3  0  5  6  5  2  5 -2  3  8  7  5 10
foo<-34
foo.ch<-as.character(foo)
foo.ch
## [1] "34"
bar<-T
bar.ch<-as.character(bar)
bar.ch
## [1] "3" "4" "8"
paste("Definitely foo: ",foo.ch,"; definitely bar: ",bar.ch,".",sep="")
## [1] "Definitely foo: 34; definitely bar: 3."
## [2] "Definitely foo: 34; definitely bar: 4."
## [3] "Definitely foo: 34; definitely bar: 8."
Coercion makes sense when there is possibilities.
as.numeric("32.4")
## [1] 32.4
Coercion that does not make sense
as.numeric("g'day mate")
## Warning: NAs introduced by coercion
## [1] NA
Example of Coercion of some values to another. However in some cases direct coercion cannot work but multiple coercion does work.
as.logical(c("1","0","1","0","0"))
## [1] NA NA NA NA NA
However this does work.
as.logical(as.numeric(c("1","0","1","0","0")))
## [1]  TRUE FALSE  TRUE FALSE FALSE
Another way of coercion.
as.numeric(as.logical(as.numeric(c("1","0","1","0","0"))))
## [1] 1 0 1 0 0
Converting or coercing a factor data into a numeric data.
baz<-factor(c("male","male","female","male"))
baz
## [1] male   male   female male  
## Levels: female male
Conversion
as.numeric(baz)
## [1] 2 2 1 2
Note for this : Because it is very important.
qux<-factor(c(2,2,3,5))
qux
## [1] 2 2 3 5
## Levels: 2 3 5
as.numeric(qux)
## [1] 1 1 2 3
2*as.numeric(qux)
## [1] 2 2 4 6
Coercion between object classes
foo<-matrix(1:4,2,2)
foo
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
Now checking
as.vector(foo) #Coercing to a vector
## [1] 1 2 3 4
Coercion of higher dimensional arrays,in order of layer or block.
bar<-array(c(8,1,9,5,5,1,3,4,3,9,8,8),dim=c(2,3,2))
bar
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]    8    9    5
## [2,]    1    5    1
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]    3    3    8
## [2,]    4    9    8
Coercing array to other data structure.
as.matrix(bar)
##       [,1]
##  [1,]    8
##  [2,]    1
##  [3,]    9
##  [4,]    5
##  [5,]    5
##  [6,]    1
##  [7,]    3
##  [8,]    4
##  [9,]    3
## [10,]    9
## [11,]    8
## [12,]    8
as.vector(bar)
##  [1] 8 1 9 5 5 1 3 4 3 9 8 8
Coercion for data type.
baz<-list(var1=foo,var2=c(T,F,T),var3=factor(c(2,3,4,4,2)))
baz
## $var1
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $var2
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8
## 
## $var3
## [1] 2 3 4 4 2
## Levels: 2 3 4
Now converting to other data structure
#as.data.frame(baz) #Error occur because they are of no similar length.
Now in the new
qux<-list(var1=c(3,4,5,1),var2=c(T,F,T,T),var3=factor(c(4,4,2,1)))
qux
## $var1
## [1] 3 4 5 1
## 
## $var2
##  [1]  3  4  8  3 -1  1 -3  1  5  3  4  8  3  4  8
## 
## $var3
## [1] 4 4 2 1
## Levels: 1 2 4
Now coercing the data structure.
#as.data.frame(qux)
#qux
Exercise 6.3

Solution (a)

foo<-array(1:36,dim=c(3,3,4))
bar<-as.vector(foo)
baz<-as.character(bar)
qux<-as.factor(baz)
quux<-bar+c(-0.1,0.1)
Checking the classes using the “class function”
class(foo) #Explicit
## [1] "array"
class(bar) #Explicit
## [1] "integer"
class(baz) #Implicit
## [1] "character"
class(qux) #Implicit
## [1] "factor"
class(quux) #Explicit
## [1] "numeric"
a<-is.numeric(foo)+is.integer((foo))
b<-is.numeric(bar)+is.integer(bar)
c<-is.numeric(baz)+is.integer(baz)
d<-is.numeric(qux)+is.integer(qux)
e<-is.numeric(quux)+is.integer(quux)

Result_fac<-factor(c(a,b,c,d,e))
Result_fac
## [1] 2 2 0 0 1
## Levels: 0 1 2
as.numeric(Result_fac)
## [1] 3 3 1 1 2
(Result_fac)==as.numeric(Result_fac)
## [1] FALSE FALSE FALSE FALSE FALSE
vec_mat<-matrix(c(2,3,4,5,6,7,8,9,10,11,12,13),3,4)
vec_mat
##      [,1] [,2] [,3] [,4]
## [1,]    2    5    8   11
## [2,]    3    6    9   12
## [3,]    4    7   10   13
as.character(vec_mat)
##  [1] "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13"

(d)i.

vec_mat2<-matrix(c(34,23,33,42,41,0,1,1,0,0,1,2,1,1,2),5,3)
vec_mat2
##      [,1] [,2] [,3]
## [1,]   34    0    1
## [2,]   23    1    2
## [3,]   33    1    1
## [4,]   42    0    1
## [5,]   41    0    2

Coercing to data.frame

A<-as.data.frame(vec_mat2)
A
##   V1 V2 V3
## 1 34  0  1
## 2 23  1  2
## 3 33  1  1
## 4 42  0  1
## 5 41  0  2

Coercing the second column to be logical values.

#A$V2<-as.logical((A$V2))
#A

Chapter 7

Basic Plotting

foo <- c(1.1,2,3.5,3.9,4.2)
bar <- c(2,2.2,-1.3,0,0.2)
length(foo)
## [1] 5
length(bar)
## [1] 5
Applying the plot basic function using R’s default behavior
plot(foo,bar)

Trying another format (i.e I can combine the two input of all the axis in touch)
baz<-cbind(foo,bar)
baz
##      foo  bar
## [1,] 1.1  2.0
## [2,] 2.0  2.2
## [3,] 3.5 -1.3
## [4,] 3.9  0.0
## [5,] 4.2  0.2
plot(baz,main="My Plot")

Wednesday 17th September 2025.

Graphical Parameters.

With the following parameters one can decorate or make beautiful a plot at their expense. These parameters include: type tells R how to plot: Either scatter without their point joined or joining the points. main,xlab,ylab Options to include the plot tiltle: The “main” handles the main title of the plot while “xlab and ylab” handles the “X and Y-axis” Labels. col Color: Used for plotting points or lines. pch Stands for point character. This selects which character to use for individual plotting points. cex Stands for character expansion. Controls the size of plotted point character. lty Stands for line type. This specifies the type of line to be used in connecting the points plotted. lwd Stands for line width. This controls the thickness of plotted lines. xlim,ylim This provides limits for the horizontal range and vertical range of the plotting region.

7.2.1 Automatic Plot Types

Adding plot type (this can also occur when plotting time series).

#plot(foo,bar,type="l")  # type="l" means line only.
#plot(foo,bar,type="b") # type="b" both lines and points.
#plot(foo,bar,type="o") # type="o" means overplotting the points with line.
plot(foo,bar,type="n") # type="n" No point or line. And it is very important for complicated plots that must be constructed in steps.

7.2.2 Title and Axis Labels

Making a Plot easier to interpret.

#plot(foo,bar,type="b",main="My Lovely Plot",xlab = "x axis label",ylab = "location y")

plot(foo,bar,main="My Lovely Plot\ntitle on two lines",type="b",xlab="",ylab="")

Notice that the Main Title is written in two lines: That’s because we place a line brake operator ()

7.2.3 Color

Adding color to a graph is far from just an aesthetic consideration. Color can make data much clearer-for example by distinguishing factor levels or emphasizing important numeric limits.

Example of Clored graphs.
#plot(foo,bar,type="b",main="My Lovely plot",xlab = "",ylab="",col=2)

plot(foo,bar,type="b",main="My Lovely plot",xlab = "",ylab="",col="seagreen4")

Plot on second spot.
plot(foo,bar,type="b",xlab="",ylab="",col="blue",pch=8,lty=5,cex=1,lwd=5,xlim=c(-10,5),ylim = c(-3,3))

Third Plot
plot(foo,bar,type="b",main="My lovely Plot",xlab="",ylab="",col=2,pch=1,cex=0.8,lty=2,lwd=2,xlim=c(3,5),ylim=c(-0.5,0.2))

Fourth Plot
plot(foo,bar,type="b",main="My lovely Plot",xlab="",ylab="",col="blue",pch=8,cex=2,lwd=2,lty=2)

Thursday 18th September 2025

Line and Point Appearance

Usig pch,lty and cex to make choice of point character and the tpype of line to be used!

plot(foo,bar,type="p",main="My lovely Plot",xlab="",ylab="",col=1:7,pch=1:25,lty=2,cex=2.3,lwd=3.3)

Trying something

plot(c(1:8),c(1:8),type="p",main = "col=",xlab="",ylab="",pch=21,bg=c("black", "red", "green", "blue", "skyblue","maroon2","yellow","grey"),col="black")

From chat Gpt

pch_values <- 21
colors <- c("red", "blue", "green", "purple", "gray")

plot(1:5, 1:5, type="b",
     pch = pch_values, 
     col = "black", 
     bg = colors, 
     cex = 3, lwd = 2)

Plot for pch

#plot(seq(5,25),
 #seq(5,25),
#type="b", # xlab="", # ylab="",
#main="pch=",
# pch=1:25,
# cex=2.3)

plot for lty

plot(foo, bar,
     type = "b",
     main = "My lovely plot",
     xlab = "X-axis",
     ylab = "Y-axis",
     col = 4,
     pch = 8,
     lty = 2,
     cex = 2.3,
     lwd = 3.3)

Second plot on top.

plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="",col=6,pch=15,lty=3,cex=0.7,lwd=2)

Friday 19th September 2025.

Welcome to Plotting Region Limits.

there are basic arguments for the limit functions given a plot: xlim and ylim. We supply numeric parameters into this function as thus: c(lower,upper).

Consider the following examples:

plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="",col=4,pch=8,lty=2,cex=2.3,lwd=3.3,xlim=c(-10,5),ylim=c(-3,3))

Second example

plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="",col=6,pch=15,lty=3,cex=0.7,lwd=,xlim=c(3,5),ylim=c(-0.5,0.2))

The beauty of plotting is in knowing the arguments for every aesthetic needed to beatify the plotting outcome.

7.3 Adding Points, Lines, and Text to an Existing Plot.

Ready to use funcytion in R that adds to a plot without refreshing or clearing the windows:

Note the word: “Canvas”! points Adds points lines,abline,segments Adds lines text Writes text arrows Adds arrows legend Adds a legend

The syntax for calling and setting parameters for these functions is the same as plot.

Example on this platform.

Loading a set of 20 data: on x and y object vector.

Plotting an ellaborate final plot of some hypothetical data.

Ten lines of Code were used to build this plot in it’s entirety (plus one additional line to add the legend). The plot as it looks at each step, is given.

Step by step methodical codes for a desired output:

x<-1:20
y<-c(-1.49,3.37,2.59,-2.78,-3.94,-0.92,6.43,8.51,3.41,-8.23,-12.01,-6.58,2.87,14.12,9.63,-4.58,-14.78,-11.67,1.17,15.62)
#1.Creating a empty plot

plot(x,y,type="n",main="")


#2. The "abline" function and it's #use.
#Note: The "abline" function adds #straight lines spanning a plot, as #thus;


abline(h=c(-5,5),col="red",lty=2,lwd=2)


#3. Adding shorter lines with #"segments".


segments(x0=c(5,15),y0=c(-5,-5),x1=c(5,15),y1=c(5,5),col="red",lty=3,lwd=2)


#4. Adding specific coordinates from #x and y values with the function #"point" to beautify the plot with #needed aes functions.


points(x[y>=5],y[y>=5],pch=4,col="darkmagenta",cex=2)


#5.The same code as that of 4, but #this time we extracts the values of #y, less or equal to -5, and assign #+ to the points and set their #colors to dark green.


points(x[y<=-5],y[y<=-5],pch=3,col="darkgreen",cex=2)


#6. Adding blue "sweet spot" points #slightly complicated.


points(x[(x>=5&y<=15)&(y>-5&y<5)],y[(x>=5&y<=15)&(y>-5&y<5)],pch=19,col="blue")


#7.Plotting No graphical parameters #with default black.


points(x[(x<5|x>15)&(y>-5&y<5)],y[(x<5|x>15)&(y>-5&y<5)])


# To draw lines connecting the #coordinates  in x and y  with #"lines".


lines(x,y,lty=4)


#9. Adding arrows pointing the sweet #point with "arrows".


arrows(x0=8,y0=14,x1=11,y1=2.5)


#10.  Adding Lael to the Plot #outcome with "text"


text(x=8,y=15,label="sweet")

#11.Adding Legend with the "legend" #function.

legend("bottomleft",
legend=c("overall process","sweet","standard","too big","too small","sweet y range","sweet x range"),
pch=c(NA,19,1,4,3,NA,NA),lty=c(4,NA,NA,NA,NA,2,3),col=c("black","darkmagenta","darkgreen","red","red"),lwd=c(1,NA,NA,NA,NA,2,2),pt.cex=c(NA,1,1,2,2,NA,NA),cex=0.5)

Note: The first argument sets where the legend should be placed.

Exercise 7.1 solution to (a)

x<--3:3
y<-7:13

plot(x,y,type="n",main="" )
abline(h=c(7,13),col="grey",lty=2,lwd=2,cex=2)
abline(v=c(-3,3),col="grey",lty=2,lwd=2,cex=2)
arrows(x0=-2.5,y0=7.5,x1=-1,y1=9.5,angle =15)
arrows(x0=-2.5,y0=10,x1=-1,y1=10)
arrows(x0=-2.5,y0=12.5,x1=-1,y1=10.5)
arrows(x0=2.5,y0=7.5,x1=1,y1=9.5)
arrows(x0=2.5,y0=10,x1=1,y1=10)
arrows(x0=2.5,y0=12.5,x1=1,y1=10.5)
text(x=0,y=10,labels="SOMETHING\n PROFOUND"
     ,cex=1)

Week 9

Monday 22nd September 2025.

Exercise 7.1 Continues (b) The plot

# Build data frame
Bag <- data.frame(
  Weight = c(55,85,75,42,93,63,58,75,89,67),
  Height = c(161,185,174,154,188,178,170,167,181,178),
  Sex = factor(c("female","male","male","female",
                 "male","male","female","male","male","female"))
)

# Define mappings explicitly by factor levels
col_map <- c(female = "red", male = "blue")
pch_map <- c(female = 17,    male = 16)

# Scatter plot
plot(
  Bag$Weight, Bag$Height,
  col = col_map[Bag$Sex],
  pch = pch_map[Bag$Sex],
  xlab = "Weight (kg)",
  ylab = "Height (cm)",
  main = "Scatterplot of Weight vs Height by Sex"
)

# Legend
legend(
  "topleft",
  legend = names(col_map),
  col = col_map,
  pch = pch_map,
  title = "Sex",
  cex = 0.8
)

Tuesday 23rd September 2025.

7.4 The ggplot2 Package.

Apart from the R’s built in graphical tools (often called base R graphics or traditional R graphics), we have a more advanced and human base suite of graphical tools: ggplot 2, a prominent contributed package which offers particular powerful alternatives to the standard plotting procedures in R. The gg stands for grammer of graphics.

7.4.1 A quik plot with “qplot”

Underlying Procedure for ggplot2: Installation and loading the “ggplot2” package

#install.packages("ggplot2")
library("ggplot2")

An Example using the “qplot” known as (quick plot) function.

foo<-c(1.1,2,3.5,3.9,4.2)
bar<-c(2,2.2,-1.3,0,0.2)

#Producing a qplot version of the plot in 7.1.
qplot(foo,bar,type="p",main="My lovely Plot",xlab="x axis label",ylab="location y")
## Warning in geom_point(type = "p"): Ignoring unknown parameters: `type`

#See the clear difference between qplot and traditional R graphics.

baz<-plot(foo,bar)

baz  # Displays NULL
## NULL
#But now check this out...
qux<-qplot(foo,bar)
qux #Behaves like an object vector.

7.4.2 Setting Apperance Constants with Geoms To add and customize points and lines in a ggplot2 graphic, rather than using a long list of arguments or secondary functions executed separately (such as points or lines). You can modify the object using ggplot2’s convenient suite of geometric modifiers , known as geoms.

Example: Adding geoms to the qplot object using the + operator.

qplot(foo,bar,geom="blank")+geom_point()+geom_line()

Without adding arguments in the geom function it automatically uses the defualt R setting.

Now specifying some literal arguments:

qplot(foo,bar,geom = "blank")+geom_point(size=3,shape=6,color="blue")+geom_line(color="red",linetype=2,linewidth=0.6)

Point character (pch) is to “shape” and character expansion (cex) is to “size” in ggplot2.

Example: Applying those arguments in the geom function with the object oriented nature of ggplot2, we can simply do these;

myqplot<-qplot(foo,bar,geom="blank")+geom_line(color="red",linetype=2)
myqplot+geom_point(size=3,shape=3,color="blue")

myqplot+geom_point(size=3,shape=7,color="blue")

There are a number of geometric modifiers that can be called using a function name beginning with geom_ in ggplot2.

x<-1:20
y<-c(-1.49,3.37,2.59,-2.78,-3.94,-0.92,6.43,8.51,3.41,-8.23,-12.01,-6.58,2.87,14.12,9.63,-4.58,-14.78,-11.67,1.17,15.62)

ptype<-rep(NA,length(x))
ptype[y>=5]<-"too_big"
ptype[y<=-5]<-"too_small"
ptype[(x>=5&x<=15)&(y>-5&y<5)]<-"sweet"
ptype[(x<5|x>15)&(y>-5&y<5)]<-"standard"
ptype<-factor(ptype)
ptype
##  [1] standard  standard  standard  standard  sweet     sweet     too_big  
##  [8] too_big   sweet     too_small too_small too_small sweet     too_big  
## [15] too_big   standard  too_small too_small standard  too_big  
## Levels: standard sweet too_big too_small
#Now you have  a factor with woo values sorted into four levels

qplot(x,y,color=ptype,shape=ptype)+
# Initial call to qplot which maps point cahracter tor points.
geom_point(size=4)+geom_line(mapping = aes(group=1),
  color="black",lty=2)+
  geom_hline(mapping=aes(yintercept = c(-5,5)),color="red")+
  geom_segment(mapping = aes(x=5,y=-5,xend = 5,yend=5),color="red",lty=3)+
  geom_segment(mapping=aes(x=15,y=-5,xend=15,yend=5),color="red",lty=3)

Exercise 7.2 Solution:

Bag<-data.frame('Weight(kg)'=c(55,85,75,42,93,63,58,75,89,67),'Height(cm)'=c(161,185,174,154,188,178,170,167,181,178),Sex=factor(c("female","male","male","female","male","male","female","male","male","female")))
Bag
##    Weight.kg. Height.cm.    Sex
## 1          55        161 female
## 2          85        185   male
## 3          75        174   male
## 4          42        154 female
## 5          93        188   male
## 6          63        178   male
## 7          58        170 female
## 8          75        167   male
## 9          89        181   male
## 10         67        178 female
# Rename columns once for simplicity
names(Bag) <- c("Weight", "Height", "Sex")

# Plot with ggplot2
ggplot(Bag, aes(x = Weight, y = Height, color = Sex, shape = Sex)) +
  geom_point(size = 3) +
  labs(
    title = "Scatterplot of Weight vs Height by Sex",
    x = "Weight (kg)",
    y = "Height (cm)"
  ) +
  theme_minimal()

Wednesday 24th September 2025.

Reading and Writing Files.

R-Ready Data Sets. To bring up a window lsting R’s ready to use data sets, we shall apply “data()”

data()

The exact list that appears depends on what contributed packages have been installed from CRAN.

8.1.1 Built-in Data Sets

To see a summary of the data sets contained in the package, you can use the “library” function as follows:

#library(help="datasets")

Look at te first 15 records of Chickweight : Row is to records and column is to variables.

ChickWeight[1:15,]
##    weight Time Chick Diet
## 1      42    0     1    1
## 2      51    2     1    1
## 3      59    4     1    1
## 4      64    6     1    1
## 5      76    8     1    1
## 6      93   10     1    1
## 7     106   12     1    1
## 8     125   14     1    1
## 9     149   16     1    1
## 10    171   18     1    1
## 11    199   20     1    1
## 12    205   21     1    1
## 13     40    0     2    1
## 14     49    2     2    1
## 15     58    4     2    1
Contributed Data Sets
#install.packages("tseries"
#library(tseries)
#library(help="tseries")

#To access the dataset "ice.river" we shall perform the following:
data("ice.river")
ice.river[1:15,]
##       flow.vat flow.jok prec temp
##  [1,]    16.10     30.2  8.1  0.9
##  [2,]    19.20     29.0  4.4  1.6
##  [3,]    14.50     28.4  7.0  0.1
##  [4,]    11.00     27.8  0.0  0.6
##  [5,]    13.60     27.8  0.0  2.0
##  [6,]    12.50     27.8  0.0  0.8
##  [7,]    10.50     27.8  1.9  1.4
##  [8,]    10.10     27.8  1.2  1.3
##  [9,]     9.68     27.8  0.0  2.2
## [10,]     9.02     27.3  0.1  0.1
## [11,]     8.80     27.3  0.0  3.0
## [12,]     8.58     27.3  0.2 -0.2
## [13,]     8.14     26.2  1.8 -2.6
## [14,]     7.50     25.2  0.2 -3.8
## [15,]     7.92     26.7  0.2  0.9
#This R-ready datasets helps us to test run our codes before we introduce any external dataset

Friday 26th September 2025**.

8.2 Reading in External Data Files Learning how to read table-format files. Easiest among the read and and import.

Header If a header is present,it’s always the first line of the file. The Delimiter the all-important delimiter is a character used to separate the entries in each line. Missing value This is another unique character string used exclusively to denote a missing value.

These files have a .txt extension (highlighting the plain-text style) or .csv (for comma-separated values).

Let’s try some examples:

mydatafile<-read.table(file="C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/8.2.1_mydatafile.txt",header=TRUE,sep=" ",na.strings = "*",stringsAsFactors=FALSE)

mydatafile
##   person age sex funny age.mon
## 1  Peter  NA   M  High     504
## 2   Lois  40   F  <NA>     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      NA
## 6  Brian  NA   M   Med      NA

Monday 29th September 2025.

I focused on Research.

Tuesday 30th September 2025.

Viewing textual output of the contents of any folder using “list.files”

#list.files("C:/Users/hp")

Setting my working Directory:

#getwd()
#setwd("C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8")

#file.choose()

Using the same command “read.table” to again read mydatafile.txt.

#mydatafile<-read.table(file=file.choose("mydatafile"),header=TRUE,sep=" ",na.strings="*",stringsAsFactors=FALSE)
  
  save.image()

Thursday 2nd October 2025.

When importing data into data frames, keep in mind the difference between character string observations and factor observations. No factor attribute information is stored in the plain-text file, but read.table will convert non-numeric values into factors by default. Here, you want to keep some of your data saved as strings, so set stringsAsFactors=FALSE, which prevents R from treating all non numeric elements as factors.This way, person, sex, and funny are all stored as character strings.

Overwriting sex and funny with factor versions of themselves

mydatafile$sex<-as.factor(mydatafile$sex)
mydatafile$funny<-factor(x=mydatafile$funny,levels=c("Low","Med","High"))

mydatafile
##   person age sex funny age.mon
## 1  Peter  NA   M  High     504
## 2   Lois  40   F  <NA>     480
## 3    Meg  17   F   Low     204
## 4  Chris  14   M   Med     168
## 5 Stewie   1   M  High      NA
## 6  Brian  NA   M   Med      NA

8.2.2 Spreadsheet Workbooks

With “read.csv” importing spreedsheet file to the R environment with the “Comma Separated Values”.

#spread<-read.csv(file="C:/Users/hp/Downloads/spreadsheetfile2.csv",header=FALSE,stringsAsFactors=TRUE)
#spread

Web-Based Files

With an Internet connection, R can read in files from a website with the same read.table command. All I need to do is to copy the Url and paste it in “read.table” command.

Example:

#dia.url<-"http://www.amstat.org/publications/jse/v9n2/4cdata.txt"
#diamonds<-read.table(dia.url)

#dia.url <- "https://jse.amstat.org/v9n2/4Cdata.txt"
#diamonds <- read.table(dia.url)
#diamonds


#Adding names to my just added online read in file.
#names(diamonds)<-c("Carat","Color","Clarity","Cert","Price")
#diamonds

#Now to read the first five records:
#diamonds[1:5,]

8.2.4 Other File Formats

There are other file formats besides .txt or .csv files that can be read into R, such as the data file format .dat. These files can also be imported using read.table, though they may contain extra information at the top that must be skipped using the optional skip argument.Other contributed packages on CRAN can help R handle files from various database management systems (DBMSs). For example, the RODBC package (Ripley and Lapsley, 2013) lets you query Microsoft Access databases and return the results as a data frame object. Other interfaces include the packages RMySQL (James and DebRoy, 2012) and RJDBC (Urbanek, 2013)

8.3 Writing out Data Files and Plots

The function for writing table-format files to your computer is write.table.

Example:

# You supply a data frame object as x, and this function writes its contents to
#a new file with a specified name, delimiter, and missing value string. For example, the following line takes the mydatafile object from Section 8.2 and writes it to a file:

table.write<-write.table(x=mydatafile,file="C:/Users/hp/Downloads/8.2.1_mydatafile.txt",sep="@",na="??",quote=FALSE,row.names=FALSE)

data("iris")
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
#which(iris==iris$Species)

cat_r<-rnorm(c(4,2,3,8:16,19:20,1,5:7,18,17))
hist(cat_r)

summary(cat_r)
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -1.91513 -0.41278  0.11219  0.02462  0.81444  2.20449
mean(cat_r)
## [1] 0.02461866
median(cat_r)
## [1] 0.1121938
summary(cat_r)
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -1.91513 -0.41278  0.11219  0.02462  0.81444  2.20449
#readr::read_file("Alushi's Weekly_Rpt.Rmd") |> stringr::str_view_all("\\p{C}")
library(tidyr)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(caret)
## Loading required package: lattice
library(rpart)
library(rpart.plot)
library(randomForest)
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
## 
##     combine
## The following object is masked from 'package:ggplot2':
## 
##     margin
library(ROCR)
library(gbm)
## Loaded gbm 2.2.2
## This version of gbm is no longer under development. Consider transitioning to gbm3, https://github.com/gbm-developers/gbm3
library(corrplot)
## corrplot 0.95 loaded
library(stringr)
library(GGally)

data<-read.csv("C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/HEART_DATA.csv")
head(data)
##   age anaemia creatinine_phosphokinase diabetes ejection_fraction
## 1  75       0                      582        0                20
## 2  55       0                     7861        0                38
## 3  65       0                      146        0                20
## 4  50       1                      111        0                20
## 5  65       1                      160        1                20
## 6  90       1                       47        0                40
##   high_blood_pressure platelets serum_creatinine serum_sodium sex smoking time
## 1                   1    265000              1.9          130   1       0    4
## 2                   0    263358              1.1          136   1       0    6
## 3                   0    162000              1.3          129   1       1    7
## 4                   0    210000              1.9          137   1       0    7
## 5                   0    327000              2.7          116   0       0    8
## 6                   1    204000              2.1          132   1       1    8
##   DEATH_EVENT
## 1           1
## 2           1
## 3           1
## 4           1
## 5           1
## 6           1
#Cleaning of data
#Checking missing values
sum(which(is.na(data)))
## [1] 0
# Removing missing values
clean_data<-na.omit(data)  #Removing missing values

#Checking for duplicate
sum(duplicated(clean_data))
## [1] 0
#Checking the data type of target cell
class(clean_data$DEATH_EVENT)
## [1] "integer"
#Converting target data to an interest data type
clean_data$DEATH_EVENT<-factor(clean_data$DEATH_EVENT)
#Checking the interest data type
glimpse(clean_data)
## Rows: 299
## Columns: 13
## $ age                      <dbl> 75, 55, 65, 50, 65, 90, 75, 60, 65, 80, 75, 6…
## $ anaemia                  <int> 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, …
## $ creatinine_phosphokinase <int> 582, 7861, 146, 111, 160, 47, 246, 315, 157, …
## $ diabetes                 <int> 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, …
## $ ejection_fraction        <int> 20, 38, 20, 20, 20, 40, 15, 60, 65, 35, 38, 2…
## $ high_blood_pressure      <int> 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, …
## $ platelets                <dbl> 265000, 263358, 162000, 210000, 327000, 20400…
## $ serum_creatinine         <dbl> 1.90, 1.10, 1.30, 1.90, 2.70, 2.10, 1.20, 1.1…
## $ serum_sodium             <int> 130, 136, 129, 137, 116, 132, 137, 131, 138, …
## $ sex                      <int> 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, …
## $ smoking                  <int> 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, …
## $ time                     <int> 4, 6, 7, 7, 8, 8, 10, 10, 10, 10, 10, 10, 11,…
## $ DEATH_EVENT              <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, …
head(clean_data$DEATH_EVENT)
## [1] 1 1 1 1 1 1
## Levels: 0 1
head(clean_data)
##   age anaemia creatinine_phosphokinase diabetes ejection_fraction
## 1  75       0                      582        0                20
## 2  55       0                     7861        0                38
## 3  65       0                      146        0                20
## 4  50       1                      111        0                20
## 5  65       1                      160        1                20
## 6  90       1                       47        0                40
##   high_blood_pressure platelets serum_creatinine serum_sodium sex smoking time
## 1                   1    265000              1.9          130   1       0    4
## 2                   0    263358              1.1          136   1       0    6
## 3                   0    162000              1.3          129   1       1    7
## 4                   0    210000              1.9          137   1       0    7
## 5                   0    327000              2.7          116   0       0    8
## 6                   1    204000              2.1          132   1       1    8
##   DEATH_EVENT
## 1           1
## 2           1
## 3           1
## 4           1
## 5           1
## 6           1
#Classification: We classify when we have binary data type.
glimpse(clean_data)
## Rows: 299
## Columns: 13
## $ age                      <dbl> 75, 55, 65, 50, 65, 90, 75, 60, 65, 80, 75, 6…
## $ anaemia                  <int> 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, …
## $ creatinine_phosphokinase <int> 582, 7861, 146, 111, 160, 47, 246, 315, 157, …
## $ diabetes                 <int> 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, …
## $ ejection_fraction        <int> 20, 38, 20, 20, 20, 40, 15, 60, 65, 35, 38, 2…
## $ high_blood_pressure      <int> 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, …
## $ platelets                <dbl> 265000, 263358, 162000, 210000, 327000, 20400…
## $ serum_creatinine         <dbl> 1.90, 1.10, 1.30, 1.90, 2.70, 2.10, 1.20, 1.1…
## $ serum_sodium             <int> 130, 136, 129, 137, 116, 132, 137, 131, 138, …
## $ sex                      <int> 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, …
## $ smoking                  <int> 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, …
## $ time                     <int> 4, 6, 7, 7, 8, 8, 10, 10, 10, 10, 10, 10, 11,…
## $ DEATH_EVENT              <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, …
#Using EDA

#selecting only numeric variables for correlation.
numeric_data<-clean_data[,sapply(clean_data,is.numeric)] #glimpse and head are having the same function. One is base and the other is from "dplyr"

# Correlation matrix
if(ncol(numeric_data)<1){# check if we have at least two numeric variables
   cor_matrix<-cor(numeric_data,method="pearson")
   print("Correlation Matrix:")
   print(cor_matrix)
   
   #Visualize correlation matrix
   library(corrplot)
 corrplot(cor_matrix,method="circle")
} else {
   print("Not enough numeric variables for a correlation matrix.")
}
## [1] "Not enough numeric variables for a correlation matrix."
# Scatterplot Matrix
#install.packages("GGally",dependencies = TRUE)
library(GGally)


data
##        age anaemia creatinine_phosphokinase diabetes ejection_fraction
## 1   75.000       0                      582        0                20
## 2   55.000       0                     7861        0                38
## 3   65.000       0                      146        0                20
## 4   50.000       1                      111        0                20
## 5   65.000       1                      160        1                20
## 6   90.000       1                       47        0                40
## 7   75.000       1                      246        0                15
## 8   60.000       1                      315        1                60
## 9   65.000       0                      157        0                65
## 10  80.000       1                      123        0                35
## 11  75.000       1                       81        0                38
## 12  62.000       0                      231        0                25
## 13  45.000       1                      981        0                30
## 14  50.000       1                      168        0                38
## 15  49.000       1                       80        0                30
## 16  82.000       1                      379        0                50
## 17  87.000       1                      149        0                38
## 18  45.000       0                      582        0                14
## 19  70.000       1                      125        0                25
## 20  48.000       1                      582        1                55
## 21  65.000       1                       52        0                25
## 22  65.000       1                      128        1                30
## 23  68.000       1                      220        0                35
## 24  53.000       0                       63        1                60
## 25  75.000       0                      582        1                30
## 26  80.000       0                      148        1                38
## 27  95.000       1                      112        0                40
## 28  70.000       0                      122        1                45
## 29  58.000       1                       60        0                38
## 30  82.000       0                       70        1                30
## 31  94.000       0                      582        1                38
## 32  85.000       0                       23        0                45
## 33  50.000       1                      249        1                35
## 34  50.000       1                      159        1                30
## 35  65.000       0                       94        1                50
## 36  69.000       0                      582        1                35
## 37  90.000       1                       60        1                50
## 38  82.000       1                      855        1                50
## 39  60.000       0                     2656        1                30
## 40  60.000       0                      235        1                38
## 41  70.000       0                      582        0                20
## 42  50.000       0                      124        1                30
## 43  70.000       0                      571        1                45
## 44  72.000       0                      127        1                50
## 45  60.000       1                      588        1                60
## 46  50.000       0                      582        1                38
## 47  51.000       0                     1380        0                25
## 48  60.000       0                      582        1                38
## 49  80.000       1                      553        0                20
## 50  57.000       1                      129        0                30
## 51  68.000       1                      577        0                25
## 52  53.000       1                       91        0                20
## 53  60.000       0                     3964        1                62
## 54  70.000       1                       69        1                50
## 55  60.000       1                      260        1                38
## 56  95.000       1                      371        0                30
## 57  70.000       1                       75        0                35
## 58  60.000       1                      607        0                40
## 59  49.000       0                      789        0                20
## 60  72.000       0                      364        1                20
## 61  45.000       0                     7702        1                25
## 62  50.000       0                      318        0                40
## 63  55.000       0                      109        0                35
## 64  45.000       0                      582        0                35
## 65  45.000       0                      582        0                80
## 66  60.000       0                       68        0                20
## 67  42.000       1                      250        1                15
## 68  72.000       1                      110        0                25
## 69  70.000       0                      161        0                25
## 70  65.000       0                      113        1                25
## 71  41.000       0                      148        0                40
## 72  58.000       0                      582        1                35
## 73  85.000       0                     5882        0                35
## 74  65.000       0                      224        1                50
## 75  69.000       0                      582        0                20
## 76  60.000       1                       47        0                20
## 77  70.000       0                       92        0                60
## 78  42.000       0                      102        1                40
## 79  75.000       1                      203        1                38
## 80  55.000       0                      336        0                45
## 81  70.000       0                       69        0                40
## 82  67.000       0                      582        0                50
## 83  60.000       1                       76        1                25
## 84  79.000       1                       55        0                50
## 85  59.000       1                      280        1                25
## 86  51.000       0                       78        0                50
## 87  55.000       0                       47        0                35
## 88  65.000       1                       68        1                60
## 89  44.000       0                       84        1                40
## 90  57.000       1                      115        0                25
## 91  70.000       0                       66        1                45
## 92  60.000       0                      897        1                45
## 93  42.000       0                      582        0                60
## 94  60.000       1                      154        0                25
## 95  58.000       0                      144        1                38
## 96  58.000       1                      133        0                60
## 97  63.000       1                      514        1                25
## 98  70.000       1                       59        0                60
## 99  60.000       1                      156        1                25
## 100 63.000       1                       61        1                40
## 101 65.000       1                      305        0                25
## 102 75.000       0                      582        0                45
## 103 80.000       0                      898        0                25
## 104 42.000       0                     5209        0                30
## 105 60.000       0                       53        0                50
## 106 72.000       1                      328        0                30
## 107 55.000       0                      748        0                45
## 108 45.000       1                     1876        1                35
## 109 63.000       0                      936        0                38
## 110 45.000       0                      292        1                35
## 111 85.000       0                      129        0                60
## 112 55.000       0                       60        0                35
## 113 50.000       0                      369        1                25
## 114 70.000       1                      143        0                60
## 115 60.000       1                      754        1                40
## 116 58.000       1                      400        0                40
## 117 60.000       1                       96        1                60
## 118 85.000       1                      102        0                60
## 119 65.000       1                      113        1                60
## 120 86.000       0                      582        0                38
## 121 60.000       1                      737        0                60
## 122 66.000       1                       68        1                38
## 123 60.000       0                       96        1                38
## 124 60.000       1                      582        0                30
## 125 60.000       0                      582        0                40
## 126 43.000       1                      358        0                50
## 127 46.000       0                      168        1                17
## 128 58.000       1                      200        1                60
## 129 61.000       0                      248        0                30
## 130 53.000       1                      270        1                35
## 131 53.000       1                     1808        0                60
## 132 60.000       1                     1082        1                45
## 133 46.000       0                      719        0                40
## 134 63.000       0                      193        0                60
## 135 81.000       0                     4540        0                35
## 136 75.000       0                      582        0                40
## 137 65.000       1                       59        1                60
## 138 68.000       1                      646        0                25
## 139 62.000       0                      281        1                35
## 140 50.000       0                     1548        0                30
## 141 80.000       0                      805        0                38
## 142 46.000       1                      291        0                35
## 143 50.000       0                      482        1                30
## 144 61.000       1                       84        0                40
## 145 72.000       1                      943        0                25
## 146 50.000       0                      185        0                30
## 147 52.000       0                      132        0                30
## 148 64.000       0                     1610        0                60
## 149 75.000       1                      582        0                30
## 150 60.000       0                     2261        0                35
## 151 72.000       0                      233        0                45
## 152 62.000       0                       30        1                60
## 153 50.000       0                      115        0                45
## 154 50.000       0                     1846        1                35
## 155 65.000       1                      335        0                35
## 156 60.000       1                      231        1                25
## 157 52.000       1                       58        0                35
## 158 50.000       0                      250        0                25
## 159 85.000       1                      910        0                50
## 160 59.000       1                      129        0                45
## 161 66.000       1                       72        0                40
## 162 45.000       1                      130        0                35
## 163 63.000       1                      582        0                40
## 164 50.000       1                     2334        1                35
## 165 45.000       0                     2442        1                30
## 166 80.000       0                      776        1                38
## 167 53.000       0                      196        0                60
## 168 59.000       0                       66        1                20
## 169 65.000       0                      582        1                40
## 170 70.000       0                      835        0                35
## 171 51.000       1                      582        1                35
## 172 52.000       0                     3966        0                40
## 173 70.000       1                      171        0                60
## 174 50.000       1                      115        0                20
## 175 65.000       0                      198        1                35
## 176 60.000       1                       95        0                60
## 177 69.000       0                     1419        0                40
## 178 49.000       1                       69        0                50
## 179 63.000       1                      122        1                60
## 180 55.000       0                      835        0                40
## 181 40.000       0                      478        1                30
## 182 59.000       1                      176        1                25
## 183 65.000       0                      395        1                25
## 184 75.000       0                       99        0                38
## 185 58.000       1                      145        0                25
## 186 60.667       1                      104        1                30
## 187 50.000       0                      582        0                50
## 188 60.000       0                     1896        1                25
## 189 60.667       1                      151        1                40
## 190 40.000       0                      244        0                45
## 191 80.000       0                      582        1                35
## 192 64.000       1                       62        0                60
## 193 50.000       1                      121        1                40
## 194 73.000       1                      231        1                30
## 195 45.000       0                      582        0                20
## 196 77.000       1                      418        0                45
## 197 45.000       0                      582        1                38
## 198 65.000       0                      167        0                30
## 199 50.000       1                      582        1                20
## 200 60.000       0                     1211        1                35
## 201 63.000       1                     1767        0                45
## 202 45.000       0                      308        1                60
## 203 70.000       0                       97        0                60
## 204 60.000       0                       59        0                25
## 205 78.000       1                       64        0                40
## 206 50.000       1                      167        1                45
## 207 40.000       1                      101        0                40
## 208 85.000       0                      212        0                38
## 209 60.000       1                     2281        1                40
## 210 49.000       0                      972        1                35
## 211 70.000       0                      212        1                17
## 212 50.000       0                      582        0                62
## 213 78.000       0                      224        0                50
## 214 48.000       1                      131        1                30
## 215 65.000       1                      135        0                35
## 216 73.000       0                      582        0                35
## 217 70.000       0                     1202        0                50
## 218 54.000       1                      427        0                70
## 219 68.000       1                     1021        1                35
## 220 55.000       0                      582        1                35
## 221 73.000       0                      582        0                20
## 222 65.000       0                      118        0                50
## 223 42.000       1                       86        0                35
## 224 47.000       0                      582        0                25
## 225 58.000       0                      582        1                25
## 226 75.000       0                      675        1                60
## 227 58.000       1                       57        0                25
## 228 55.000       1                     2794        0                35
## 229 65.000       0                       56        0                25
## 230 72.000       0                      211        0                25
## 231 60.000       0                      166        0                30
## 232 70.000       0                       93        0                35
## 233 40.000       1                      129        0                35
## 234 53.000       1                      707        0                38
## 235 53.000       1                      582        0                45
## 236 77.000       1                      109        0                50
## 237 75.000       0                      119        0                50
## 238 70.000       0                      232        0                30
## 239 65.000       1                      720        1                40
## 240 55.000       1                      180        0                45
## 241 70.000       0                       81        1                35
## 242 65.000       0                      582        1                30
## 243 40.000       0                       90        0                35
## 244 73.000       1                     1185        0                40
## 245 54.000       0                      582        1                38
## 246 61.000       1                       80        1                38
## 247 55.000       0                     2017        0                25
## 248 64.000       0                      143        0                25
## 249 40.000       0                      624        0                35
## 250 53.000       0                      207        1                40
## 251 50.000       0                     2522        0                30
## 252 55.000       0                      572        1                35
## 253 50.000       0                      245        0                45
## 254 70.000       0                       88        1                35
## 255 53.000       1                      446        0                60
## 256 52.000       1                      191        1                30
## 257 65.000       0                      326        0                38
## 258 58.000       0                      132        1                38
## 259 45.000       1                       66        1                25
## 260 53.000       0                       56        0                50
## 261 55.000       0                       66        0                40
## 262 62.000       1                      655        0                40
## 263 65.000       1                      258        1                25
## 264 68.000       1                      157        1                60
## 265 61.000       0                      582        1                38
## 266 50.000       1                      298        0                35
## 267 55.000       0                     1199        0                20
## 268 56.000       1                      135        1                38
## 269 45.000       0                      582        1                38
## 270 40.000       0                      582        1                35
## 271 44.000       0                      582        1                30
## 272 51.000       0                      582        1                40
## 273 67.000       0                      213        0                38
## 274 42.000       0                       64        0                40
## 275 60.000       1                      257        1                30
## 276 45.000       0                      582        0                38
## 277 70.000       0                      618        0                35
## 278 70.000       0                      582        1                38
## 279 50.000       1                     1051        1                30
## 280 55.000       0                       84        1                38
## 281 70.000       0                     2695        1                40
## 282 70.000       0                      582        0                40
## 283 42.000       0                       64        0                30
## 284 65.000       0                     1688        0                38
## 285 50.000       1                       54        0                40
## 286 55.000       1                      170        1                40
## 287 60.000       0                      253        0                35
## 288 45.000       0                      582        1                55
## 289 65.000       0                      892        1                35
## 290 90.000       1                      337        0                38
## 291 45.000       0                      615        1                55
## 292 60.000       0                      320        0                35
## 293 52.000       0                      190        1                38
## 294 63.000       1                      103        1                35
## 295 62.000       0                       61        1                38
## 296 55.000       0                     1820        0                38
## 297 45.000       0                     2060        1                60
## 298 45.000       0                     2413        0                38
## 299 50.000       0                      196        0                45
##     high_blood_pressure platelets serum_creatinine serum_sodium sex smoking
## 1                     1    265000             1.90          130   1       0
## 2                     0    263358             1.10          136   1       0
## 3                     0    162000             1.30          129   1       1
## 4                     0    210000             1.90          137   1       0
## 5                     0    327000             2.70          116   0       0
## 6                     1    204000             2.10          132   1       1
## 7                     0    127000             1.20          137   1       0
## 8                     0    454000             1.10          131   1       1
## 9                     0    263358             1.50          138   0       0
## 10                    1    388000             9.40          133   1       1
## 11                    1    368000             4.00          131   1       1
## 12                    1    253000             0.90          140   1       1
## 13                    0    136000             1.10          137   1       0
## 14                    1    276000             1.10          137   1       0
## 15                    1    427000             1.00          138   0       0
## 16                    0     47000             1.30          136   1       0
## 17                    0    262000             0.90          140   1       0
## 18                    0    166000             0.80          127   1       0
## 19                    1    237000             1.00          140   0       0
## 20                    0     87000             1.90          121   0       0
## 21                    1    276000             1.30          137   0       0
## 22                    1    297000             1.60          136   0       0
## 23                    1    289000             0.90          140   1       1
## 24                    0    368000             0.80          135   1       0
## 25                    1    263358             1.83          134   0       0
## 26                    0    149000             1.90          144   1       1
## 27                    1    196000             1.00          138   0       0
## 28                    1    284000             1.30          136   1       1
## 29                    0    153000             5.80          134   1       0
## 30                    0    200000             1.20          132   1       1
## 31                    1    263358             1.83          134   1       0
## 32                    0    360000             3.00          132   1       0
## 33                    1    319000             1.00          128   0       0
## 34                    0    302000             1.20          138   0       0
## 35                    1    188000             1.00          140   1       0
## 36                    0    228000             3.50          134   1       0
## 37                    0    226000             1.00          134   1       0
## 38                    1    321000             1.00          145   0       0
## 39                    0    305000             2.30          137   1       0
## 40                    0    329000             3.00          142   0       0
## 41                    1    263358             1.83          134   1       1
## 42                    1    153000             1.20          136   0       1
## 43                    1    185000             1.20          139   1       1
## 44                    1    218000             1.00          134   1       0
## 45                    0    194000             1.10          142   0       0
## 46                    0    310000             1.90          135   1       1
## 47                    1    271000             0.90          130   1       0
## 48                    1    451000             0.60          138   1       1
## 49                    1    140000             4.40          133   1       0
## 50                    0    395000             1.00          140   0       0
## 51                    1    166000             1.00          138   1       0
## 52                    1    418000             1.40          139   0       0
## 53                    0    263358             6.80          146   0       0
## 54                    1    351000             1.00          134   0       0
## 55                    0    255000             2.20          132   0       1
## 56                    0    461000             2.00          132   1       0
## 57                    0    223000             2.70          138   1       1
## 58                    0    216000             0.60          138   1       1
## 59                    1    319000             1.10          136   1       1
## 60                    1    254000             1.30          136   1       1
## 61                    1    390000             1.00          139   1       0
## 62                    1    216000             2.30          131   0       0
## 63                    0    254000             1.10          139   1       1
## 64                    0    385000             1.00          145   1       0
## 65                    0    263358             1.18          137   0       0
## 66                    0    119000             2.90          127   1       1
## 67                    0    213000             1.30          136   0       0
## 68                    0    274000             1.00          140   1       1
## 69                    0    244000             1.20          142   0       0
## 70                    0    497000             1.83          135   1       0
## 71                    0    374000             0.80          140   1       1
## 72                    0    122000             0.90          139   1       1
## 73                    0    243000             1.00          132   1       1
## 74                    0    149000             1.30          137   1       1
## 75                    0    266000             1.20          134   1       1
## 76                    0    204000             0.70          139   1       1
## 77                    1    317000             0.80          140   0       1
## 78                    0    237000             1.20          140   1       0
## 79                    1    283000             0.60          131   1       1
## 80                    1    324000             0.90          140   0       0
## 81                    0    293000             1.70          136   0       0
## 82                    0    263358             1.18          137   1       1
## 83                    0    196000             2.50          132   0       0
## 84                    1    172000             1.80          133   1       0
## 85                    1    302000             1.00          141   0       0
## 86                    0    406000             0.70          140   1       0
## 87                    1    173000             1.10          137   1       0
## 88                    1    304000             0.80          140   1       0
## 89                    1    235000             0.70          139   1       0
## 90                    1    181000             1.10          144   1       0
## 91                    0    249000             0.80          136   1       1
## 92                    0    297000             1.00          133   1       0
## 93                    0    263358             1.18          137   0       0
## 94                    0    210000             1.70          135   1       0
## 95                    1    327000             0.70          142   0       0
## 96                    1    219000             1.00          141   1       0
## 97                    1    254000             1.30          134   1       0
## 98                    0    255000             1.10          136   0       0
## 99                    1    318000             1.20          137   0       0
## 100                   0    221000             1.10          140   0       0
## 101                   0    298000             1.10          141   1       0
## 102                   1    263358             1.18          137   1       0
## 103                   0    149000             1.10          144   1       1
## 104                   0    226000             1.00          140   1       1
## 105                   1    286000             2.30          143   0       0
## 106                   1    621000             1.70          138   0       1
## 107                   0    263000             1.30          137   1       0
## 108                   0    226000             0.90          138   1       0
## 109                   0    304000             1.10          133   1       1
## 110                   0    850000             1.30          142   1       1
## 111                   0    306000             1.20          132   1       1
## 112                   0    228000             1.20          135   1       1
## 113                   0    252000             1.60          136   1       0
## 114                   0    351000             1.30          137   0       0
## 115                   1    328000             1.20          126   1       0
## 116                   0    164000             1.00          139   0       0
## 117                   1    271000             0.70          136   0       0
## 118                   0    507000             3.20          138   0       0
## 119                   1    203000             0.90          140   0       0
## 120                   0    263358             1.83          134   0       0
## 121                   1    210000             1.50          135   1       1
## 122                   1    162000             1.00          136   0       0
## 123                   0    228000             0.75          140   0       0
## 124                   1    127000             0.90          145   0       0
## 125                   0    217000             3.70          134   1       0
## 126                   0    237000             1.30          135   0       0
## 127                   1    271000             2.10          124   0       0
## 128                   0    300000             0.80          137   0       0
## 129                   1    267000             0.70          136   1       1
## 130                   0    227000             3.40          145   1       0
## 131                   1    249000             0.70          138   1       1
## 132                   0    250000             6.10          131   1       0
## 133                   1    263358             1.18          137   0       0
## 134                   1    295000             1.30          145   1       1
## 135                   0    231000             1.18          137   1       1
## 136                   0    263358             1.18          137   1       0
## 137                   0    172000             0.90          137   0       0
## 138                   0    305000             2.10          130   1       0
## 139                   0    221000             1.00          136   0       0
## 140                   1    211000             0.80          138   1       0
## 141                   0    263358             1.10          134   1       0
## 142                   0    348000             0.90          140   0       0
## 143                   0    329000             0.90          132   0       0
## 144                   1    229000             0.90          141   0       0
## 145                   1    338000             1.70          139   1       1
## 146                   0    266000             0.70          141   1       1
## 147                   0    218000             0.70          136   1       1
## 148                   0    242000             1.00          137   1       0
## 149                   0    225000             1.83          134   1       0
## 150                   1    228000             0.90          136   1       0
## 151                   1    235000             2.50          135   0       0
## 152                   1    244000             0.90          139   1       0
## 153                   1    184000             0.90          134   1       1
## 154                   0    263358             1.18          137   1       1
## 155                   1    235000             0.80          136   0       0
## 156                   0    194000             1.70          140   1       0
## 157                   0    277000             1.40          136   0       0
## 158                   0    262000             1.00          136   1       1
## 159                   0    235000             1.30          134   1       0
## 160                   1    362000             1.10          139   1       1
## 161                   1    242000             1.20          134   1       0
## 162                   0    174000             0.80          139   1       1
## 163                   0    448000             0.90          137   1       1
## 164                   0     75000             0.90          142   0       0
## 165                   0    334000             1.10          139   1       0
## 166                   1    192000             1.30          135   0       0
## 167                   0    220000             0.70          133   1       1
## 168                   0     70000             2.40          134   1       0
## 169                   0    270000             1.00          138   0       0
## 170                   1    305000             0.80          133   0       0
## 171                   0    263358             1.50          136   1       1
## 172                   0    325000             0.90          140   1       1
## 173                   1    176000             1.10          145   1       1
## 174                   0    189000             0.80          139   1       0
## 175                   1    281000             0.90          137   1       1
## 176                   0    337000             1.00          138   1       1
## 177                   0    105000             1.00          135   1       1
## 178                   0    132000             1.00          140   0       0
## 179                   0    267000             1.20          145   1       0
## 180                   0    279000             0.70          140   1       1
## 181                   0    303000             0.90          136   1       0
## 182                   0    221000             1.00          136   1       1
## 183                   0    265000             1.20          136   1       1
## 184                   1    224000             2.50          134   1       0
## 185                   0    219000             1.20          137   1       1
## 186                   0    389000             1.50          136   1       0
## 187                   0    153000             0.60          134   0       0
## 188                   0    365000             2.10          144   0       0
## 189                   1    201000             1.00          136   0       0
## 190                   1    275000             0.90          140   0       0
## 191                   0    350000             2.10          134   1       0
## 192                   0    309000             1.50          135   0       0
## 193                   0    260000             0.70          130   1       0
## 194                   0    160000             1.18          142   1       1
## 195                   1    126000             1.60          135   1       0
## 196                   0    223000             1.80          145   1       0
## 197                   1    263358             1.18          137   0       0
## 198                   0    259000             0.80          138   0       0
## 199                   1    279000             1.00          134   0       0
## 200                   0    263358             1.80          113   1       1
## 201                   0     73000             0.70          137   1       0
## 202                   1    377000             1.00          136   1       0
## 203                   1    220000             0.90          138   1       0
## 204                   1    212000             3.50          136   1       1
## 205                   0    277000             0.70          137   1       1
## 206                   0    362000             1.00          136   0       0
## 207                   0    226000             0.80          141   0       0
## 208                   0    186000             0.90          136   1       0
## 209                   0    283000             1.00          141   0       0
## 210                   1    268000             0.80          130   0       0
## 211                   1    389000             1.00          136   1       1
## 212                   1    147000             0.80          140   1       1
## 213                   0    481000             1.40          138   1       1
## 214                   1    244000             1.60          130   0       0
## 215                   1    290000             0.80          134   1       0
## 216                   1    203000             1.30          134   1       0
## 217                   1    358000             0.90          141   0       0
## 218                   1    151000             9.00          137   0       0
## 219                   0    271000             1.10          134   1       0
## 220                   1    371000             0.70          140   0       0
## 221                   0    263358             1.83          134   1       0
## 222                   0    194000             1.10          145   1       1
## 223                   0    365000             1.10          139   1       1
## 224                   0    130000             0.80          134   1       0
## 225                   0    504000             1.00          138   1       0
## 226                   0    265000             1.40          125   0       0
## 227                   0    189000             1.30          132   1       1
## 228                   1    141000             1.00          140   1       0
## 229                   0    237000             5.00          130   0       0
## 230                   0    274000             1.20          134   0       0
## 231                   0     62000             1.70          127   0       0
## 232                   0    185000             1.10          134   1       1
## 233                   0    255000             0.90          137   1       0
## 234                   0    330000             1.40          137   1       1
## 235                   0    305000             1.10          137   1       1
## 236                   1    406000             1.10          137   1       0
## 237                   1    248000             1.10          148   1       0
## 238                   0    173000             1.20          132   1       0
## 239                   0    257000             1.00          136   0       0
## 240                   0    263358             1.18          137   1       1
## 241                   1    533000             1.30          139   0       0
## 242                   0    249000             1.30          136   1       1
## 243                   0    255000             1.10          136   1       1
## 244                   1    220000             0.90          141   0       0
## 245                   0    264000             1.80          134   1       0
## 246                   0    282000             1.40          137   1       0
## 247                   0    314000             1.10          138   1       0
## 248                   0    246000             2.40          135   1       0
## 249                   0    301000             1.00          142   1       1
## 250                   0    223000             1.20          130   0       0
## 251                   1    404000             0.50          139   0       0
## 252                   0    231000             0.80          143   0       0
## 253                   1    274000             1.00          133   1       0
## 254                   1    236000             1.20          132   0       0
## 255                   1    263358             1.00          139   1       0
## 256                   1    334000             1.00          142   1       1
## 257                   0    294000             1.70          139   0       0
## 258                   1    253000             1.00          139   1       0
## 259                   0    233000             0.80          135   1       0
## 260                   0    308000             0.70          135   1       1
## 261                   0    203000             1.00          138   1       0
## 262                   0    283000             0.70          133   0       0
## 263                   0    198000             1.40          129   1       0
## 264                   0    208000             1.00          140   0       0
## 265                   0    147000             1.20          141   1       0
## 266                   0    362000             0.90          140   1       1
## 267                   0    263358             1.83          134   1       1
## 268                   0    133000             1.70          140   1       0
## 269                   0    302000             0.90          140   0       0
## 270                   0    222000             1.00          132   1       0
## 271                   1    263358             1.60          130   1       1
## 272                   0    221000             0.90          134   0       0
## 273                   0    215000             1.20          133   0       0
## 274                   0    189000             0.70          140   1       0
## 275                   0    150000             1.00          137   1       1
## 276                   1    422000             0.80          137   0       0
## 277                   0    327000             1.10          142   0       0
## 278                   0     25100             1.10          140   1       0
## 279                   0    232000             0.70          136   0       0
## 280                   0    451000             1.30          136   0       0
## 281                   0    241000             1.00          137   1       0
## 282                   0     51000             2.70          136   1       1
## 283                   0    215000             3.80          128   1       1
## 284                   0    263358             1.10          138   1       1
## 285                   0    279000             0.80          141   1       0
## 286                   0    336000             1.20          135   1       0
## 287                   0    279000             1.70          140   1       0
## 288                   0    543000             1.00          132   0       0
## 289                   0    263358             1.10          142   0       0
## 290                   0    390000             0.90          144   0       0
## 291                   0    222000             0.80          141   0       0
## 292                   0    133000             1.40          139   1       0
## 293                   0    382000             1.00          140   1       1
## 294                   0    179000             0.90          136   1       1
## 295                   1    155000             1.10          143   1       1
## 296                   0    270000             1.20          139   0       0
## 297                   0    742000             0.80          138   0       0
## 298                   0    140000             1.40          140   1       1
## 299                   0    395000             1.60          136   1       1
##     time DEATH_EVENT
## 1      4           1
## 2      6           1
## 3      7           1
## 4      7           1
## 5      8           1
## 6      8           1
## 7     10           1
## 8     10           1
## 9     10           1
## 10    10           1
## 11    10           1
## 12    10           1
## 13    11           1
## 14    11           1
## 15    12           0
## 16    13           1
## 17    14           1
## 18    14           1
## 19    15           1
## 20    15           1
## 21    16           0
## 22    20           1
## 23    20           1
## 24    22           0
## 25    23           1
## 26    23           1
## 27    24           1
## 28    26           1
## 29    26           1
## 30    26           1
## 31    27           1
## 32    28           1
## 33    28           1
## 34    29           0
## 35    29           1
## 36    30           1
## 37    30           1
## 38    30           1
## 39    30           0
## 40    30           1
## 41    31           1
## 42    32           1
## 43    33           1
## 44    33           0
## 45    33           1
## 46    35           1
## 47    38           1
## 48    40           1
## 49    41           1
## 50    42           1
## 51    43           1
## 52    43           1
## 53    43           1
## 54    44           1
## 55    45           1
## 56    50           1
## 57    54           0
## 58    54           0
## 59    55           1
## 60    59           1
## 61    60           1
## 62    60           1
## 63    60           0
## 64    61           1
## 65    63           0
## 66    64           1
## 67    65           1
## 68    65           1
## 69    66           1
## 70    67           1
## 71    68           0
## 72    71           0
## 73    72           1
## 74    72           0
## 75    73           1
## 76    73           1
## 77    74           0
## 78    74           0
## 79    74           0
## 80    74           0
## 81    75           0
## 82    76           0
## 83    77           1
## 84    78           0
## 85    78           1
## 86    79           0
## 87    79           0
## 88    79           0
## 89    79           0
## 90    79           0
## 91    80           0
## 92    80           0
## 93    82           0
## 94    82           1
## 95    83           0
## 96    83           0
## 97    83           0
## 98    85           0
## 99    85           0
## 100   86           0
## 101   87           0
## 102   87           0
## 103   87           0
## 104   87           0
## 105   87           0
## 106   88           1
## 107   88           0
## 108   88           0
## 109   88           0
## 110   88           0
## 111   90           1
## 112   90           0
## 113   90           0
## 114   90           1
## 115   91           0
## 116   91           0
## 117   94           0
## 118   94           0
## 119   94           0
## 120   95           1
## 121   95           0
## 122   95           0
## 123   95           0
## 124   95           0
## 125   96           1
## 126   97           0
## 127  100           1
## 128  104           0
## 129  104           0
## 130  105           0
## 131  106           0
## 132  107           0
## 133  107           0
## 134  107           0
## 135  107           0
## 136  107           0
## 137  107           0
## 138  108           0
## 139  108           0
## 140  108           0
## 141  109           1
## 142  109           0
## 143  109           0
## 144  110           0
## 145  111           1
## 146  112           0
## 147  112           0
## 148  113           0
## 149  113           1
## 150  115           0
## 151  115           1
## 152  117           0
## 153  118           0
## 154  119           0
## 155  120           0
## 156  120           0
## 157  120           0
## 158  120           0
## 159  121           0
## 160  121           0
## 161  121           0
## 162  121           0
## 163  123           0
## 164  126           1
## 165  129           1
## 166  130           1
## 167  134           0
## 168  135           1
## 169  140           0
## 170  145           0
## 171  145           0
## 172  146           0
## 173  146           0
## 174  146           0
## 175  146           0
## 176  146           0
## 177  147           0
## 178  147           0
## 179  147           0
## 180  147           0
## 181  148           0
## 182  150           1
## 183  154           1
## 184  162           1
## 185  170           1
## 186  171           1
## 187  172           1
## 188  172           1
## 189  172           0
## 190  174           0
## 191  174           0
## 192  174           0
## 193  175           0
## 194  180           0
## 195  180           1
## 196  180           1
## 197  185           0
## 198  186           0
## 199  186           0
## 200  186           0
## 201  186           0
## 202  186           0
## 203  186           0
## 204  187           0
## 205  187           0
## 206  187           0
## 207  187           0
## 208  187           0
## 209  187           0
## 210  187           0
## 211  188           0
## 212  192           0
## 213  192           0
## 214  193           1
## 215  194           0
## 216  195           0
## 217  196           0
## 218  196           1
## 219  197           0
## 220  197           0
## 221  198           1
## 222  200           0
## 223  201           0
## 224  201           0
## 225  205           0
## 226  205           0
## 227  205           0
## 228  206           0
## 229  207           0
## 230  207           0
## 231  207           1
## 232  208           0
## 233  209           0
## 234  209           0
## 235  209           0
## 236  209           0
## 237  209           0
## 238  210           0
## 239  210           0
## 240  211           0
## 241  212           0
## 242  212           0
## 243  212           0
## 244  213           0
## 245  213           0
## 246  213           0
## 247  214           1
## 248  214           0
## 249  214           0
## 250  214           0
## 251  214           0
## 252  215           0
## 253  215           0
## 254  215           0
## 255  215           0
## 256  216           0
## 257  220           0
## 258  230           0
## 259  230           0
## 260  231           0
## 261  233           0
## 262  233           0
## 263  235           1
## 264  237           0
## 265  237           0
## 266  240           0
## 267  241           1
## 268  244           0
## 269  244           0
## 270  244           0
## 271  244           0
## 272  244           0
## 273  245           0
## 274  245           0
## 275  245           0
## 276  245           0
## 277  245           0
## 278  246           0
## 279  246           0
## 280  246           0
## 281  247           0
## 282  250           0
## 283  250           0
## 284  250           0
## 285  250           0
## 286  250           0
## 287  250           0
## 288  250           0
## 289  256           0
## 290  256           0
## 291  257           0
## 292  258           0
## 293  258           0
## 294  270           0
## 295  270           0
## 296  271           0
## 297  278           0
## 298  280           0
## 299  285           0
dput(x=B,file="C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/corr_plot.jpeg")

R supports direct writing to .jpeg, .bmp, .png, and .tiff files using functions of the same names. For example, the following code uses these three steps to create a .jpeg file:.jpeg (or .jpg) — Joint Photographic Experts Group,.bmp — Bitmap Image File,.png — Portable Network Graphics and .tiff (or .tif) — Tagged Image File Format.

Corrplot <- jpeg(filename="C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/Correlation_1",width=600,height =600 )

plot(1:5,6:10,ylab="a nice ylab",xlab="here's an xlab",main="a save .jpeg plot")+
points(1:5,
       10:6,
       cex=2,
       pch=4,
       col=2)
## integer(0)
library(ggplot2)
foo <- c(1.1,2,3.5,3.9,4.2)
bar <- c(2,2.2,-1.3,0,0.2)

qplot(foo,bar,geom="blank")+
   geom_point(size=3,shape=8,color="darkgreen")+
   geom_line(color="orange",linetype=4)

# Now, to save this plot to a file, all you need is the following line:

ggsave(filename = "C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/myggplot.png")
## Saving 7 x 5 in image
# (Note that dimensions are reported if you don’t explicitly set them using
 #width and height; these will vary depending on the size of your graphics
 #device.) The result is shown in Figure 8-8.

8.4 Ad Hoc Object Read/Write Operations

For the typical R user, the most common input/output operations will probably revolve around data sets and plot images. But if you need to read or write other kinds of R objects, such as lists or arrays, you’ll need the dput and dget commands, which can handle objects in a more ad hoc style. Suppose, for example, you create this list in the current session:

somelist <- list(foo=c(5,2,45),
                 bar=matrix(data=c(TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE),nrow=3,ncol=3),
                 baz=factor(c(1,2,2,3,1,1,3),levels=1:3,ordered = TRUE))

somelist
## $foo
## [1]  5  2 45
## 
## $bar
##       [,1]  [,2]  [,3]
## [1,]  TRUE FALSE  TRUE
## [2,]  TRUE FALSE FALSE
## [3,] FALSE FALSE  TRUE
## 
## $baz
## [1] 1 2 2 3 1 1 3
## Levels: 1 < 2 < 3
# This object can itself be written to a file, which is useful if you want to
 #pass it to a colleague or open it in a new R session elsewhere. Using dput, the
 #following line stores the object as a plain-text file that is interpretable by R

dput(x=somelist,file="C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/myobject.txt")

# In technical terms, this command creates an American Standard Code
 #for Information Interchange (ASCII) representation of the ob3ject. As you
 #call dput, the object you want to write is specified as x, and the folder location
 #and name of the new plain-text file are passed to file. Figure 8-9 shows the
 #contents of the resulting file.

 #Now, let’s say you want to import this list into an R workspace. If a file
 #has been created with dput, then it can be read into any other workspace
 #using dget

newobject <- dget(file="C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/myobject.txt")

newobject
## $foo
## [1]  5  2 45
## 
## $bar
##       [,1]  [,2]  [,3]
## [1,]  TRUE FALSE  TRUE
## [2,]  TRUE FALSE FALSE
## [3,] FALSE FALSE  TRUE
## 
## $baz
## [1] 1 2 2 3 1 1 3
## Levels: 1 < 2 < 3

Exercise 8.1

#(a)
data()

# Access the built-in dataset
data("quakes")
help(quakes)   # view information about the dataset
## starting httpd help server ... done
# Select only rows where mag >= 5
q5 <- subset(quakes, mag >= 5)

# Write to a text file using '!' as a delimiter, no row names
write.table(q5, 
            file = "C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/q5.txt",  # change path to your own folder
            sep = "!", 
            row.names = FALSE)

#(ii).
# Read the file back into R
q5.dframe <- read.table("C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/q5.txt", 
                        sep = "!", 
                        header = TRUE)

# Check the imported data
head(q5.dframe)
##      lat   long depth mag stations
## 1 -26.00 184.10    42 5.4       43
## 2 -20.70 169.92   139 6.1       94
## 3 -13.64 165.96    50 6.0       83
## 4 -19.66 180.28   431 5.4       57
## 5 -16.46 180.79   498 5.2       79
## 6 -18.97 185.25   129 5.1       73
#(b)
#Using the Duncan dataset from the car package
#Step i: Install and load the package

#install.packages("car")
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## 
## The following object is masked from 'package:dplyr':
## 
##     recode
# Access the dataset
data("Duncan")
help(Duncan)

#Step ii: Plot education (x-axis) vs income (y-axis)

# Create the plot
plot(Duncan$education, Duncan$income,
     xlim = c(0, 100),
     ylim = c(0, 100),
     xlab = "Education Level",
     ylab = "Income Level",
     col = ifelse(Duncan$prestige <= 80, "black", "blue"),
     pch = 19)

# Add a legend
legend("topleft", 
       legend = c("Prestige ≤ 80", "Prestige > 80"), 
       col = c("black", "blue"), 
       pch = 19)

# Save the plot as a 500x500 pixel .png
png("C://Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/Duncan_plot.png", width = 500, height = 500)


#(c)
# Create a list containing the three datasets
exer <- list(quakes = quakes, q5.dframe = q5.dframe, Duncan = Duncan)

# Write the list to disk
save(exer, file = "C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/Exercise8-1.txt")

#write to disk
#dput(exer, file = "C:/path/to/your/folder/Exercise8-1.txt")

#Step ii: Read the list back

# Read the list back
#list.of.dataframes <- dget("C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/Exercise8-1.txt")

# Verify contents
#names(list.of.dataframes)
#lapply(list.of.dataframes, head)

#(d)
#d. Saving a ggplot as a .tiff file

#Assuming you previously created a ggplot object named myplot (for example):

library(ggplot2)

# Example plot (replace with your actual ggplot object)
myplot <- ggplot(data = mtcars, aes(x = wt, y = mpg)) + 
  geom_point() + 
  theme_minimal()

# Save as a .tiff file
ggsave("C:/Users/hp/OneDrive/Desktop/ICAMMDA/SIWES Week 8/myplot.tiff", plot = myplot, width = 5, height = 5, units = "in")

Monday 13th October 2025. Part II, (Programming).

9.1 Scoping To begin with, it’s important to understand R’s scoping rules, which determine how the language compartmentalizes objects and retrieves them in a given session. This framework also defines the situations in which dupli cate object names can exist at once. For example, you’ve used the argument data when calling matrix (Section 3.1), but data is also the name of a ready-to-use function that loads data sets from contributed packages (Section 8.1.2). In this section, you’ll gain an introductory understanding of how Rbehaves internally in these circumstances, which will help you later on when it comes to programming and executing your own functions and those of other packages.

9.1.1 Environments NOTE Technically speaking, environments don’t actually contain items. Rather, they have pointers to the location of those items in the computer’s memory. But using the “compartment” metaphor and thinking of objects “belonging to” these compartments is useful when you’re first getting a general sense of how environments work.

Technically speaking, environments don’t actually contain items. Rather, they have pointers to the location of those items in the computer’s memory. But using the “compartment” metaphor and thinking of objects “belonging to” these compartments is useful when you’re first getting a general sense of how environments work.

Global Environment The global environment is the compartment set aside for user-defined objects. Every object you’ve created or overwritten so far has resided in the global environment of your current R session.

I mentioned that a call to ls() lists all the objects, variables, and user-defined functions in the active workspace—more precisely, ls() prints the names of everything in the current global environment. Example: Starting with a new R workspace, the following code creates two objects and confirms their existence in the global environment:

foo <- 4+5
bar <- "stringtastic"
ls()
##   [1] "a"                "A"                "A2"              
##   [4] "Alushi"           "AR"               "b"               
##   [7] "B"                "Bag"              "bar"             
##  [10] "bar.ch"           "bar.mat"          "baz"             
##  [13] "boo"              "br"               "BR"              
##  [16] "c"                "C"                "cat_r"           
##  [19] "char.mat"         "char.vec"         "clean_data"      
##  [22] "col_map"          "colors"           "Corrplot"        
##  [25] "d"                "D"                "data"            
##  [28] "dframe"           "dm"               "Duncan"          
##  [31] "e"                "E"                "exer"            
##  [34] "f"                "F"                "fac.mat"         
##  [37] "fac.vec"          "firstname"        "flow.jok"        
##  [40] "flow.vat"         "foo"              "foo.ch"          
##  [43] "foo.mat"          "funny"            "g"               
##  [46] "G"                "goo"              "Greens"          
##  [49] "h"                "i"                "ice.river"       
##  [52] "iris"             "J"                "K"               
##  [55] "L"                "lab"              "Labour"          
##  [58] "logic.mat"        "logic.vec"        "m"               
##  [61] "M"                "Maori"            "mar"             
##  [64] "mob"              "moo"              "ms"              
##  [67] "my result"        "Mycob"            "mydata"          
##  [70] "mydata2"          "mydatafile"       "mydataframe"     
##  [73] "mymat"            "mynumber"         "myplot"          
##  [76] "myqplot"          "myseq"            "myseq2"          
##  [79] "myseqA"           "myvec"            "Myvec"           
##  [82] "myvec.len"        "myvec2"           "myvec3"          
##  [85] "MyvectE"          "n"                "N"               
##  [88] "National"         "new.party_factor" "new.sex_factor"  
##  [91] "newobject"        "newrecord"        "noo"             
##  [94] "num.females"      "num.males"        "num.mat1"        
##  [97] "num.mat2"         "num.vec1"         "num.vec2"        
## [100] "num1"             "num2"             "numeric_data"    
## [103] "O"                "opt.arg"          "ordfac.vec"      
## [106] "Other"            "p"                "P"               
## [109] "party"            "party.factor"     "Path"            
## [112] "pch_map"          "pch_values"       "Pol.party"       
## [115] "prec"             "ptype"            "q"               
## [118] "Q"                "q5"               "q5.dframe"       
## [121] "quakes"           "quux"             "qux"             
## [124] "r"                "R"                "result"          
## [127] "Result_fac"       "S"                "sex"             
## [130] "sex.char"         "sex.char.fac"     "sex.factor"      
## [133] "sex.num"          "sex.num.fac"      "somelist"        
## [136] "spread"           "Storestr"         "t"               
## [139] "T"                "Table"            "table.write"     
## [142] "temp"             "u"                "v"               
## [145] "vals"             "var"              "vec"             
## [148] "vec_mat"          "vec_mat2"         "vicka"           
## [151] "vicka1"           "w"                "x"               
## [154] "X"                "y"                "Y"               
## [157] "z"

Package-specific environments: Package Environments and Namespaces Each package environment actually represents several environments that control different aspects of a search for a given object. A package namespace, for example, essentially defines the visibility of its functions. (A package can have visible functions that a user is able to use and invisible functions that provide internal support to the visible functions.) Another part of the package environment handles imports designations,dealing with any functions or objects from other libraries that the package needs to import for its own functionality.

Example:To clarify this,you can think of all the ready-to-use functions and objects you’re working within this book as belonging to specific package environments.The same is true for the functions and objects of any contributed packages you’ve explicitly loaded with a call to library. You can use ls to list the items in a package environment as follows:

ls("package:graphics")
##  [1] "abline"          "arrows"          "assocplot"       "axis"           
##  [5] "Axis"            "axis.Date"       "axis.POSIXct"    "axTicks"        
##  [9] "barplot"         "barplot.default" "box"             "boxplot"        
## [13] "boxplot.default" "boxplot.matrix"  "bxp"             "cdplot"         
## [17] "clip"            "close.screen"    "co.intervals"    "contour"        
## [21] "contour.default" "coplot"          "curve"           "dotchart"       
## [25] "erase.screen"    "filled.contour"  "fourfoldplot"    "frame"          
## [29] "grconvertX"      "grconvertY"      "grid"            "hist"           
## [33] "hist.default"    "identify"        "image"           "image.default"  
## [37] "layout"          "layout.show"     "lcm"             "legend"         
## [41] "lines"           "lines.default"   "locator"         "matlines"       
## [45] "matplot"         "matpoints"       "mosaicplot"      "mtext"          
## [49] "pairs"           "pairs.default"   "panel.smooth"    "par"            
## [53] "persp"           "pie"             "plot"            "plot.default"   
## [57] "plot.design"     "plot.function"   "plot.new"        "plot.window"    
## [61] "plot.xy"         "points"          "points.default"  "polygon"        
## [65] "polypath"        "rasterImage"     "rect"            "rug"            
## [69] "screen"          "segments"        "smoothScatter"   "spineplot"      
## [73] "split.screen"    "stars"           "stem"            "strheight"      
## [77] "stripchart"      "strwidth"        "sunflowerplot"   "symbols"        
## [81] "text"            "text.default"    "title"           "xinch"          
## [85] "xspline"         "xyinch"          "yinch"

Local Environments: Each time a function is called in R,a new environment is created called the local environment,sometimes referred to as the lexical environment. Example:For example, say you call matrix and pass in the argument data, as follows:

youthspeak <- matrix(data =c("OMG","LOL","WTF","YOLO"),nrow=2,ncol=2)
youthspeak
##      [,1]  [,2]  
## [1,] "OMG" "WTF" 
## [2,] "LOL" "YOLO"
#R is not confused by other objects or functions named data in other environments ( such as the data function automatically loaded from the utils package environment, only then does R begin to widen its search for that item).

9.1.2 Search Path The search path is basically a list of the environments that R will search when an object is requested. If the object isn’t found in one environment,Rproceeds to the next one. You can view R’s search path at any time using:

search()
##  [1] ".GlobalEnv"           "package:car"          "package:carData"     
##  [4] "package:GGally"       "package:stringr"      "package:corrplot"    
##  [7] "package:gbm"          "package:ROCR"         "package:randomForest"
## [10] "package:rpart.plot"   "package:rpart"        "package:caret"       
## [13] "package:lattice"      "package:dplyr"        "package:tidyr"       
## [16] "package:tseries"      "package:ggplot2"      "package:stats"       
## [19] "package:graphics"     "package:grDevices"    "package:utils"       
## [22] "package:datasets"     "package:methods"      "Autoloads"           
## [25] "package:base"
#  For my current session, if I request a certain object at the R prompt, the program will inspect .GlobalEnv to tools:RGUI to package:stats to package:base in turn, stopping the search when the desired object is found and retrieved.

# The last destination (search path) is the empty environment .

#Check this Example
baz <- seq(0,3,length.out=5)
baz
## [1] 0.00 0.75 1.50 2.25 3.00
# You can look up the enclosing environment of any function using environment, as follows:
environment(seq)
## <environment: namespace:base>
environment(arrows)
## <environment: namespace:graphics>
#Each environment has a parent, to direct the order of the search path.
#Examining the earlier output from the call search(), you can see that the parent of package:stats, for example, is package:graphics.

#Check this:
#When you load a contributed package with a call to library, this essentially just inserts the desired package in the search path. For example, in Exercise 8.1 on page 161, you installed the contributed package car. After loading this package, your search path will include its contents.

library("car")
search()
##  [1] ".GlobalEnv"           "package:car"          "package:carData"     
##  [4] "package:GGally"       "package:stringr"      "package:corrplot"    
##  [7] "package:gbm"          "package:ROCR"         "package:randomForest"
## [10] "package:rpart.plot"   "package:rpart"        "package:caret"       
## [13] "package:lattice"      "package:dplyr"        "package:tidyr"       
## [16] "package:tseries"      "package:ggplot2"      "package:stats"       
## [19] "package:graphics"     "package:grDevices"    "package:utils"       
## [22] "package:datasets"     "package:methods"      "Autoloads"           
## [25] "package:base"
#Trying to check whether some function or object are in the environment.

#neither.here()
#nor.there

#As you get more comfortable with R and want more precise control over how it operates, it’s worth investigating in full how R handles environments.For more technical details on this, Gupta (2012) provides a particularly well written online article.

9.1.3 Reserved and Protected Names A few key terms are strictly forbidden from being used as object names in R.These reserved names are necessary in order to protect fundamental operations and data types frequently used in the language. The following identifiers are reserved: • ifandelse • for,while, and in • function • repeat, break, and next • TRUEandFALSE • Infand-Inf • NA,NaN, and NULL

# If you try to assign a new value to any of these reserved terms, an error occurs.
#NaN <- 5

#Because R is case sensitive, it’s possible to assign values to any case variant of the reserved names, but this can be confusing and is generally not advisable.

False <- "confusing"
nan <- "this is"
cat(nan,False)
## this is confusing
# Also be wary of assigning values to T and F, the abbreviations of TRUE and FALSE. The full identifiers TRUE and FALSE are reserved, but the abbreviated versions are not.
 
 T <- 42 
 F <- TRUE
 F&&TRUE
## [1] TRUE
 # To clear this obvious confusion of using F as TRUE instead of the making it remain the abbreviated value of FALSE.
 
 ls()
##   [1] "a"                "A"                "A2"              
##   [4] "Alushi"           "AR"               "b"               
##   [7] "B"                "Bag"              "bar"             
##  [10] "bar.ch"           "bar.mat"          "baz"             
##  [13] "boo"              "br"               "BR"              
##  [16] "c"                "C"                "cat_r"           
##  [19] "char.mat"         "char.vec"         "clean_data"      
##  [22] "col_map"          "colors"           "Corrplot"        
##  [25] "d"                "D"                "data"            
##  [28] "dframe"           "dm"               "Duncan"          
##  [31] "e"                "E"                "exer"            
##  [34] "f"                "F"                "fac.mat"         
##  [37] "fac.vec"          "False"            "firstname"       
##  [40] "flow.jok"         "flow.vat"         "foo"             
##  [43] "foo.ch"           "foo.mat"          "funny"           
##  [46] "g"                "G"                "goo"             
##  [49] "Greens"           "h"                "i"               
##  [52] "ice.river"        "iris"             "J"               
##  [55] "K"                "L"                "lab"             
##  [58] "Labour"           "logic.mat"        "logic.vec"       
##  [61] "m"                "M"                "Maori"           
##  [64] "mar"              "mob"              "moo"             
##  [67] "ms"               "my result"        "Mycob"           
##  [70] "mydata"           "mydata2"          "mydatafile"      
##  [73] "mydataframe"      "mymat"            "mynumber"        
##  [76] "myplot"           "myqplot"          "myseq"           
##  [79] "myseq2"           "myseqA"           "myvec"           
##  [82] "Myvec"            "myvec.len"        "myvec2"          
##  [85] "myvec3"           "MyvectE"          "n"               
##  [88] "N"                "nan"              "National"        
##  [91] "new.party_factor" "new.sex_factor"   "newobject"       
##  [94] "newrecord"        "noo"              "num.females"     
##  [97] "num.males"        "num.mat1"         "num.mat2"        
## [100] "num.vec1"         "num.vec2"         "num1"            
## [103] "num2"             "numeric_data"     "O"               
## [106] "opt.arg"          "ordfac.vec"       "Other"           
## [109] "p"                "P"                "party"           
## [112] "party.factor"     "Path"             "pch_map"         
## [115] "pch_values"       "Pol.party"        "prec"            
## [118] "ptype"            "q"                "Q"               
## [121] "q5"               "q5.dframe"        "quakes"          
## [124] "quux"             "qux"              "r"               
## [127] "R"                "result"           "Result_fac"      
## [130] "S"                "sex"              "sex.char"        
## [133] "sex.char.fac"     "sex.factor"       "sex.num"         
## [136] "sex.num.fac"      "somelist"         "spread"          
## [139] "Storestr"         "t"                "T"               
## [142] "Table"            "table.write"      "temp"            
## [145] "u"                "v"                "vals"            
## [148] "var"              "vec"              "vec_mat"         
## [151] "vec_mat2"         "vicka"            "vicka1"          
## [154] "w"                "x"                "X"               
## [157] "y"                "Y"                "youthspeak"      
## [160] "z"
 rm(list=ls())
 ls()
## character(0)

Exercise 9.1

#(a)
# List all objects in the methods package
all_methods <- ls("package:methods")

# Display the first 20
head(all_methods, 20)
##  [1] "addNextMethod"         "allNames"              "Arith"                
##  [4] "as"                    "as<-"                  "asMethodDefinition"   
##  [7] "assignClassDef"        "assignMethodsMetaData" "balanceMethodsList"   
## [10] "body<-"                "cacheGenericsMetaData" "cacheMetaData"        
## [13] "cacheMethod"           "callGeneric"           "callNextMethod"       
## [16] "canCoerce"             "cbind2"                "checkAtAssignment"    
## [19] "checkSlotAssignment"   "classesToAM"
# Find out how many total items there are
length(all_methods)
## [1] 203
#(b)
environment(read.table)  #utils
## <environment: namespace:utils>
environment(data)  #utils
## <environment: namespace:utils>
environment(matrix)  #base
## <environment: namespace:base>
environment(jpeg)   #grDevices
## <environment: namespace:grDevices>
#(c)
# List all objects in the graphics package
graphics_items <- ls("package:graphics")

# Test for character equality
"smoothScatter" %in% graphics_items
## [1] TRUE
which("smoothScatter"==graphics_items)
## [1] 71

9.2 Argument Matching: 9.2.1 Exact Other benefits of exact matching include the following: • Exactmatching is less prone to mis-specification of arguments than other matching styles. • Theorderinwhich arguments are supplied doesn’t matter. • Exactmatching is useful when a function has many possible arguments but you want to specify only a few. The main drawbacks of exact matching are clear: • Itcanbecumbersome for relatively simple operations. • Exactmatching requires the user to remember or look up the full, case sensitive tags. Example:

bar <- matrix(data=1:9,nrow=3,ncol=3,dimnames=list(c("A","B","c"),c("D","E","F")))
bar
##   D E F
## A 1 4 7
## B 2 5 8
## c 3 6 9
#This creates a 3 3 matrix object bar with a dimnames attribute for the rows and columns. Since the argument tags are fully specified, the order of the arguments doesn’t matter. You could switch around the arguments, and the function still has all the information it requires.

bar <- matrix(nrow=3,dimnames = list(c("A","B","C"),c("D","E","F")),ncol=3,data=1:9)
bar
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9

9.2.2 Partial: Here is another way to call matrix that takes advantage of partial matching:

bar <- matrix(nr=3,di=list(c("A","B","C"),c("D","E","F")),nc=3,dat=1:9)
bar
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9

Partial matching has the following benefits: • It requires less code than exact matching. • Argument tags are still visible (which limits the possibility of misspecification). • The order of supplied arguments still doesn’t matter

But partial matching also has some limitations. For one, it gets trickier if there are multiple arguments whose tags start with the same letters. Here’s an example:

#bar <- matrix(nr=3,di=list(c("A","B","C"),c("D","E","F")),nc=3,d=1:9)

#The fourth arguments matches the first.

9.2.3 Positional The most compact mode of function calling in R is positional matching. This is when you supply arguments without tags, and R interprets them based solely on their order. You can find that information in the “Usage” section of the function’s help file, or it can be printed to the console with the args function.Here’s an example:

args(matrix)
## function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) 
## NULL
#This shows the defined order of arguments of the matrix function, as well as the default value for each argument. To construct the matrix bar with positional matching, execute the following:

bar <- matrix(1:9,3,3,F,list(c("A","B","C"),c("D","E","F")))
bar
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9
# The benefits of positional matching are as follows:
# • Shorter, cleaner code, particularly for routine tasks
# • No need to remember specific argument tags

#Check this example: If I write a certain argument.
#bar <- matrix(1:9,3,3,list(c("A","B","C"),c("D","E","F"))) Error occured.

#This brings us to the drawbacks of positional matching:
 #• Youmustlookupandexactly match the defined order of arguments.
 #• Readingcode written by someone else can be more difficult, especially when it includes unfamiliar function

9.2.4 Mixed Since each matching style has pros and cons, it’s quite common, and perfectly legal, to mix these three styles in a single function call.For instance, you can avoid the type of error shown in the previous example like so:

bar <- matrix(1:9,3,3,dim=list(c("A","B","C"),c("D","E","F")))
bar
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9

9.2.5 Dot-Dot-Dot: Use of Ellipses Many functions exhibit variadic behavior. That is, they can accept any number of arguments, and it’s up to the user to decide how many arguments to provide. The functions c, data.frame, and list are all like this. When you call a function like data.frame, you can specify any number of members as arguments.This flexibility is achieved in R through the special dot-dot-dot designa tion (…), also called the ellipsis. This construct allows the user to supply any number of data vectors (these become the columns in the final data frame). You can see whether an ellipsis is used in a function on the function’s help page or with args. Looking at data.frame, notice the first argument slot is an ellipsis:

args(data.frame)
## function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, 
##     fix.empty.names = TRUE, stringsAsFactors = FALSE) 
## NULL
#The first group includes functions such as c, data.frame, and list, where the ellipsis always represents the “main ingredients” in the function call. That is, the objective of the function is to use contents of the ellipsis in the resulting object or output.
#The second group consists of functions where the ellipsis is meant as a supplementary or potential repository of optional arguments.


#Here’s an example of the ellipsis used for supplementary arguments with the generic plot function:

args(plot)
## function (x, y, ...) 
## NULL

Exercise 9.2

#(a)
seq(from=-4,to=4,by=0.2) #Using positional matching to create a matrix.
##  [1] -4.0 -3.8 -3.6 -3.4 -3.2 -3.0 -2.8 -2.6 -2.4 -2.2 -2.0 -1.8 -1.6 -1.4 -1.2
## [16] -1.0 -0.8 -0.6 -0.4 -0.2  0.0  0.2  0.4  0.6  0.8  1.0  1.2  1.4  1.6  1.8
## [31]  2.0  2.2  2.4  2.6  2.8  3.0  3.2  3.4  3.6  3.8  4.0
#(bi)
array(8:1,dim=c(2,2,2)) #Mixed Matching
## , , 1
## 
##      [,1] [,2]
## [1,]    8    6
## [2,]    7    5
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    4    2
## [2,]    3    1
#ii)
rep(1:2,3)  #Positional matching
## [1] 1 2 1 2 1 2
#iii)
seq(from=10,to=8,length=5) #Mixed matching
## [1] 10.0  9.5  9.0  8.5  8.0
#iv)
sort(decreasing=T,x=c(2,1,1,2,0.3,3,1.3))  #Exact matching
## [1] 3.0 2.0 2.0 1.3 1.0 1.0 0.3
#v)
which(matrix(c(T,F,T,T),2,2))  #Positional matching
## [1] 1 3 4
#vi)
which(matrix(c(T,F,T,T),2,2),a=T)  #Partial matching
##      row col
## [1,]   1   1
## [2,]   1   2
## [3,]   2   2
#(c)
x=1:5
y=3:7
B <- plot.default(x,y,type="b",pch=19,xlab="",ylab="",lwd=0.5,lty=2,col="red")

args(B)
## NULL