setwd("C:/Users/favou/OneDrive/Documents") 

Detailed descriptions of topics covered

HEY<-matrix(data=c(4.3,3.1,8.2,8.2,3.2,0.9,1.6,6.5),4,2,byrow=TRUE)
HEY            
##      [,1] [,2]
## [1,]  4.3  3.1
## [2,]  8.2  8.2
## [3,]  3.2  0.9
## [4,]  1.6  6.5
HI<-HEY[-3,]

dim(x=HI)
## [1] 3 2
#c
HEY[,2]<-sort(x=HEY[,2],decreasing = FALSE)
HEY
##      [,1] [,2]
## [1,]  4.3  0.9
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,]  1.6  8.2
#D
HE<-HEY[-4,-1]
HE
## [1] 0.9 3.1 6.5
HE<-matrix(data=c(HEY[-4,-1]))
HE
##      [,1]
## [1,]  0.9
## [2,]  3.1
## [3,]  6.5
#E
HIP<-HEY[3:4,]
HIP
##      [,1] [,2]
## [1,]  3.2  6.5
## [2,]  1.6  8.2
#f
HEY[c(4,1),2:1]<- -1/2*diag(HIP)
HEY
##      [,1] [,2]
## [1,] -4.1 -4.1
## [2,]  8.2  3.1
## [3,]  3.2  6.5
## [4,] -1.6 -1.6
HEY[c(4,1),2:1]<- -0.5*diag(HIP)




A <- matrix(data=c(-3,2,893,0.17),nrow=2,ncol=2)
A
##      [,1]   [,2]
## [1,]   -3 893.00
## [2,]    2   0.17
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
matrix(data=c(1,2,3,4,5,6),nrow=2,ncol=3,byrow=FALSE)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
matrix(data=c(1:6),nrow=2,ncol=3,byrow=TRUE)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
rbind(1:3,4:6)      
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
cbind (c(1,4),c(2,5),c(3,6))       
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
rbind (c(1,3),c(4,6))
##      [,1] [,2]
## [1,]    1    3
## [2,]    4    6
####### MATRIX DIMENSIONS
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
dim(mymat)
## [1] 4 3
nrow(mymat)
## [1] 4
ncol(mymat)
## [1] 3
dim(mymat)[2]
## [1] 3
A <- matrix(data=c(-3,3,893,0.17),nrow=2,ncol=2)
A
##      [,1]   [,2]
## [1,]   -3 893.00
## [2,]    3   0.17
B <-matrix(data=c(-3,2,893,0.17),nrow=4,ncol=1)
B
##        [,1]
## [1,]  -3.00
## [2,]   2.00
## [3,] 893.00
## [4,]   0.17
matrix (data=c(1,2,3,4,5,6),nrow=2,ncol=3,byrow=FALSE)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
 matrix(data=c(1,2,3,4,5,6),nrow=2,ncol=3,byrow=TRUE)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
 rbind(1:3,4:6)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
 cbind(c(1,4),c(2,5),c(3,6))
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6

Non-Numeric Values

#EXERCISE 4.3a
fat<- c(7,5,6,1,2,10,8,3,8,2)
fat
##  [1]  7  5  6  1  2 10  8  3  8  2
we<-fat>=5
we
##  [1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE
ban<-fat[which(x=fat>=5)]     ###i
ban
## [1]  7  5  6 10  8  8
fat[-which(x=fat>=5)]   ###ii
## [1] 1 2 3 2
bank<-matrix(ban,nrow=2,ncol=3,byrow=TRUE)   # 4.3b
bank
##      [,1] [,2] [,3]
## [1,]    7    5    6
## [2,]   10    8    8
bank[bank==8]<-bank[1,2]^2
bank
##      [,1] [,2] [,3]
## [1,]    7    5    6
## [2,]   10   25   25
all(bank[bank<=25]&bank[bank>4])
## [1] TRUE
all((bank<=25)&(bank>4))
## [1] TRUE
#4.2.2 Concatenation
qax<-c('awesome',"R","is")
qax
## [1] "awesome" "R"       "is"
length(x=qax)
## [1] 3
nchar(qax)
## [1] 7 1 2
cat(qax[2],qax[3],qax[1],"!")
## R is awesome !
paste(qax[2],qax[3],"totally",qax[1],"!")
## [1] "R is totally awesome !"
paste(qax[2],qax[3],"totally",qax[1],"!",sep = "---")
## [1] "R---is---totally---awesome---!"
paste(qax[2],qax[3],"totally",qax[1],"!",sep = "")
## [1] "Ristotallyawesome!"
paste(qax[2],qax[3],"totally",qax[1],"!",sep = " ")
## [1] "R is totally awesome !"
paste(qax[2],qax[3],"totally",qax[1],"!",sep = "//")
## [1] "R//is//totally//awesome//!"
cat("Do you think ",qax[2]," ",qax[3]," ",qax[1],"?",sep="")
## Do you think R is awesome?
ka<-"Do you think"
ka
## [1] "Do you think"
paste(ka," ",qax[2]," ",qax[3]," ",qax[1],"?",sep="")
## [1] "Do you think R is awesome?"
a<-3
a
## [1] 3
b<-4.4
b
## [1] 4.4
cat("The value stored as 'a' is ",a,".",sep="")
## The value stored as 'a' is 3.
paste("The value stored as 'a' is ",b,".",sep="")
## [1] "The value stored as 'a' is 4.4."
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 totallyTRUE."
## 4.2.3 Escape Sequences
cat("here is a string\nsplit\tto neww\b\n\n\tlines")
## here is a string
## split    to neww
## 
##  lines
cat("here is a string\nsplit\tto neww\b \n\n\tlines")
## here is a string
## split    to neww 
## 
##  lines
cat("here is a string\nsplit\tto neww\b \n\tlines")
## here is a string
## split    to neww 
##  lines
cat("I really want a blackslash: \\nand a double quote: \"")
## I really want a blackslash: \nand a double quote: "
cat("I really want a blackslash: \\\nand a double quote: \"")
## I really want a blackslash: \
## and a double quote: "
paste("I really want a blackslash: \\\nand a double quote: \"")
## [1] "I really want a blackslash: \\\nand a double quote: \""

Lists and Data Frames

#####EXERCISE 5.1i
fav<-list(seq(-4,4, length.out=20),matrix(data = c(F,T,T,T,F,T,T,F,F),nrow=3, ncol=3,
                                          byrow=FALSE),String=c("don","quixote"),factor(c("LOW","MED","LOW","MED","MED","HIGH")))
favvy<-fav[[2]]
favie<-favvy[c(2,1),c(2,3)]
favie    ##OR
##       [,1]  [,2]
## [1,] FALSE FALSE
## [2,]  TRUE  TRUE
fav[[2]][c(2,1),c(2,3)]
##       [,1]  [,2]
## [1,] FALSE FALSE
## [2,]  TRUE  TRUE
fav[[3]][2]<-sub(pattern="quixote", replacement ="Quixote",x=fav[[3]][2])
fav
## [[1]]
##  [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
## 
## [[2]]
##       [,1]  [,2]  [,3]
## [1,] FALSE  TRUE  TRUE
## [2,]  TRUE FALSE FALSE
## [3,]  TRUE  TRUE FALSE
## 
## $String
## [1] "don"     "Quixote"
## 
## [[4]]
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
fav[[3]][1]<-sub(pattern = "don", replacement = "Don",x=fav[[3]][1])
fav
## [[1]]
##  [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
## 
## [[2]]
##       [,1]  [,2]  [,3]
## [1,] FALSE  TRUE  TRUE
## [2,]  TRUE FALSE FALSE
## [3,]  TRUE  TRUE FALSE
## 
## $String
## [1] "Don"     "Quixote"
## 
## [[4]]
## [1] LOW  MED  LOW  MED  MED  HIGH
## Levels: HIGH LOW MED
cat("\"windmills! ATTACK!\n\t","-\\", fav[[3]][1], " ",fav[[3]][2], "/-", sep="")
## "windmills! ATTACK!
##  -\Don Quixote/-
which(fav[[4]]=="MED")
## [1] 2 4 5
which(x=fav[[4]]=="MED")
## [1] 2 4 5
# Exercise 5.1B
newlist<-list(facs=fav[[4]],nums=c(3,2.1,3.3,4,1.5,4.9),oldlist=fav[1:3])
newlist
## $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[[1]]
##  [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[[2]]
##       [,1]  [,2]  [,3]
## [1,] FALSE  TRUE  TRUE
## [2,]  TRUE FALSE FALSE
## [3,]  TRUE  TRUE FALSE
## 
## $oldlist$String
## [1] "Don"     "Quixote"
newlist$facs[newlist$nums >=3]
## [1] LOW  LOW  MED  HIGH
## Levels: HIGH LOW MED
newlist$flags<-rep(newlist$oldlist[[2]][,3],times=2)
newlist$flags
## [1]  TRUE FALSE FALSE  TRUE FALSE FALSE
newlist
## $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[[1]]
##  [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[[2]]
##       [,1]  [,2]  [,3]
## [1,] FALSE  TRUE  TRUE
## [2,]  TRUE FALSE FALSE
## [3,]  TRUE  TRUE FALSE
## 
## $oldlist$String
## [1] "Don"     "Quixote"
## 
## 
## $flags
## [1]  TRUE FALSE FALSE  TRUE FALSE FALSE
newlist$nums[newlist$flags!=TRUE]
## [1] 2.1 3.3 1.5 4.9
newlist$oldlist$String<-"Don Quixote"

# Exercise 5.2d
mydata<-data.frame(person=c("Peter","Lois","Meg","Chris","Stewie","Brian"),
                   age=c(42,40,17,14,1,7),
                   sex=factor(c("M","F","F","M","M","M")),
                   funny=factor(c("High","High","Low","Med","High","Med"),
                                levels = c("Low","Med","High"),ordered = T),
                   age.mon=c(504,480,204,168,12,84),stringsAsFactors = F)
mydata
##   person age sex funny age.mon
## 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  Brian   7   M   Med      84
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  Brian   7   M   Med
### Exercise 5.2e
mydataframe<-rbind(mydata2)
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  Brian   7   M   Med
#f
mydataframe[mydataframe$sex=="F"&(mydataframe$funny=="Med"|mydataframe$funny=="High"),c(1,2)]
##   person age
## 2   Lois  40
#g
nameswiths<-mydataframe[substr(mydataframe$person,start=0,stop=1)=="S",1:ncol(mydataframe)]
nameswiths
##   person age sex funny
## 5 Stewie   1   M  High
mydataframe[substr(mydataframe$person,start=0,stop=1)=="S",]
##   person age sex funny
## 5 Stewie   1   M  High

##6.1.3 NA

fat<-c("character","a",NA,"with","string",NA)
fat
## [1] "character" "a"         NA          "with"      "string"    NA
bat<-factor(c("blue",NA,NA,"blue","green","blue",NA,"red","red",NA,"green"))
bat
##  [1] blue  <NA>  <NA>  blue  green blue  <NA>  red   red   <NA>  green
## Levels: blue green red
baz<-matrix(c(1:3,NA,5,6,NA,8,NA), nrow=3,ncol=3)
baz
##      [,1] [,2] [,3]
## [1,]    1   NA   NA
## [2,]    2    5    8
## [3,]    3    6   NA
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
is.na(x=qux)
##  [1]  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
## [13] FALSE  TRUE
which(x=is.nan(x=qux))
## [1]  7 14
which(x=(is.na(x=qux)& !is.nan(x=qux)))
## [1]  1  4 11
quux<-na.omit(object = 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"
3+2.1*NA-4
## [1] NA
3*c(1,2,NA,NA,NaN,6)
## [1]   3   6  NA  NA NaN  18
NA>76
## [1] NA
76<NaN
## [1] NA
# 6.2.4 As-Dot Coercion Functions
1:4+c(T,F,F,T)
## [1] 2 2 3 5
FoO<-34
bAR<-T
paste("Definitely FoO: ",FoO,"; definitely bAR: ",bAR,".",sep = "")
## [1] "Definitely FoO: 34; definitely bAR: TRUE."
as.numeric(c(T,F,F,T))
## [1] 1 0 0 1
1:4+as.numeric(c(T,F,F,T))
## [1] 2 2 3 5
Foo<-34
Foo.ch<-as.character(Foo)
Foo.ch
## [1] "34"
BAr<-T
BAr
## [1] TRUE
BAr.ch<-as.character(BAr)
BAr.ch
## [1] "TRUE"
paste("Definitely Foo: ",Foo.ch,"; definitely BAr: ",BAr.ch,".",sep = "" )
## [1] "Definitely Foo: 34; definitely BAr: TRUE."
as.numeric("g'dat mate")
## Warning: NAs introduced by coercion
## [1] NA
as.logical(c("1","0","1","0","0"))
## [1] NA NA NA NA NA
as.logical(as.numeric(c("1","0","1","0","0")))
## [1]  TRUE FALSE  TRUE FALSE FALSE
BAZ<-factor(x=c("male","male","female","male"))
BAZ
## [1] male   male   female male  
## Levels: female male
as.numeric(BAZ)
## [1] 2 2 1 2
QUX<-factor(x=c(2,2,3,5))
QUX
## [1] 2 2 3 5
## Levels: 2 3 5
as.numeric(QUX)
## [1] 1 1 2 3
fOO<-matrix(data=1:4,nrow = 2,ncol = 2)
fOO
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
as.vector(fOO)
## [1] 1 2 3 4
baR<-array(data=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
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
BAz<-list(var1=fOO,var2=c(T,F,T),var3=factor(x=c(2,3,4,4,2)))

Basic Plotting

 #7.3 Adding Points, Lines, and Text to an Existing Plot
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)
x[y<=-5]
## [1] 10 11 12 17 18
y[y<=-5]
## [1]  -8.23 -12.01  -6.58 -14.78 -11.67
plot(x,y,type = "n",main = "")
abline(h=c(-5,5),col="red",lty=2,lwd=2)
segments(x0=c(5,15),y0=c(-5,-5),x1=c(5,15),y1=c(5,5),col="red",lty = 3,lwd = 2)
points(x[y>=5],y[y>=5],pch=4,col="darkmagenta",cex=2)
points(x[y<= -5],y[y<=-5],pch=3,col="darkgreen",cex=2)
points(x[(x>=5&x<=15)&(y>-5&y<5)],y[(x>=5&x<=15)&(y>-5&y<5)],pch=19,col="blue")
points(x[(x<5|x>15)&(y>-5&y<5)],y[(x<5|x>15)&(y>-5&y<5)])
lines(x,y,lty=4)
arrows(x0=8,y0=14,x1=11,y1=2.5)
text(x=8,y=15,labels="sweet spot")
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","blue","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)

##Exercise 7.1
plot(-3:3, 7:13, type="n", xlab="", ylab="")
text(x=0, y=10, labels="SOMETHING\nPROFOUND")
abline(v=c(-3,3), lty=2, lwd=3, col=8)
abline(h=c(7,13), lty=2, lwd=3, col=8)
arrows(x0=c(-3,-3,-3,3,3,3),
       y0=c(7,10,13,7,10,13),
       x1=c(-1,-1,-1,1,1,1),
       y1=c(9.5,10,10.5,9.5,10,10.5),
       col=8, lwd=3)

#Exercise 7.1b
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 <- c("female", "male", "male", "female", "male", "male", "female", "male", "male", "female")

plot(Weight,Height)

colour_1<-c("male"="blue","female"="red")
colors<-colour_1[sex]
pch_map <- c("male" = 16, "female" = 17)
pch_vals <- pch_map[sex]
plot(Weight,Height,
     col=colors,
     pch=pch_vals,
     xlab = "Weight(kg)",
     ylab = "Height(cm)",
     main= "Height vs. weight by Sex")
legend("topleft",legend=c("male","female"),col=c("blue","red"),pch=c(16,17))

#Additional tools to refine and annotate plots:
sex <- factor(c("male", "female", "male", "female"))
height <- c(180, 165, 175, 160)
plot(sex, height)
text(x = 1, y = 180, labels = "Tall Male")
abline(h = 170, col = "red", lty = 2)
legend("bottomright", legend = c("Male", "Female"), col = c("blue", "red"), pch = c(16, 17))

###CHAPTER9

#CHAPTER9
foo<-4+5
foo
## [1] 9
bar<-"stringtastic"
bar
## [1] "stringtastic"
ls()
##  [1] "a"           "A"           "b"           "B"           "ban"        
##  [6] "bank"        "bar"         "baR"         "bAR"         "BAr"        
## [11] "BAr.ch"      "bat"         "baz"         "BAz"         "BAZ"        
## [16] "colors"      "colour_1"    "fat"         "fav"         "favie"      
## [21] "favvy"       "foo"         "fOO"         "Foo"         "FoO"        
## [26] "Foo.ch"      "HE"          "height"      "Height"      "HEY"        
## [31] "HI"          "HIP"         "ka"          "mydata"      "mydata2"    
## [36] "mydataframe" "mymat"       "nameswiths"  "newlist"     "pch_map"    
## [41] "pch_vals"    "qax"         "quux"        "qux"         "QUX"        
## [46] "sex"         "we"          "Weight"      "x"           "y"
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"
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
youthspeak<-matrix(data =c("OMG","LOL","WTF","YOLO"),nrow=2,ncol=2)
youthspeak
##      [,1]  [,2]  
## [1,] "OMG" "WTF" 
## [2,] "LOL" "YOLO"
# 9.1.2 Search Path
search()
## [1] ".GlobalEnv"        "package:stats"     "package:graphics" 
## [4] "package:grDevices" "package:utils"     "package:datasets" 
## [7] "package:methods"   "Autoloads"         "package:base"
baz <- seq(from=0,to=3,length.out=5)
baz
## [1] 0.00 0.75 1.50 2.25 3.00
environment(seq)
## <environment: namespace:base>
environment(arrows)
## <environment: namespace:graphics>
library("car")
## Loading required package: carData
library("car")
search()
##  [1] ".GlobalEnv"        "package:car"       "package:carData"  
##  [4] "package:stats"     "package:graphics"  "package:grDevices"
##  [7] "package:utils"     "package:datasets"  "package:methods"  
## [10] "Autoloads"         "package:base"
False <- "confusing"
nan <- "this is"
cat(nan,False)
## this is confusing
T <- 42
T
## [1] 42
F <- TRUE
F
## [1] TRUE
F&&TRUE
## [1] TRUE
ls()
##  [1] "a"           "A"           "b"           "B"           "ban"        
##  [6] "bank"        "bar"         "baR"         "bAR"         "BAr"        
## [11] "BAr.ch"      "bat"         "baz"         "BAz"         "BAZ"        
## [16] "colors"      "colour_1"    "F"           "False"       "fat"        
## [21] "fav"         "favie"       "favvy"       "foo"         "fOO"        
## [26] "Foo"         "FoO"         "Foo.ch"      "HE"          "height"     
## [31] "Height"      "HEY"         "HI"          "HIP"         "ka"         
## [36] "mydata"      "mydata2"     "mydataframe" "mymat"       "nameswiths" 
## [41] "nan"         "newlist"     "pch_map"     "pch_vals"    "qax"        
## [46] "quux"        "qux"         "QUX"         "sex"         "T"          
## [51] "we"          "Weight"      "x"           "y"           "youthspeak"
rm(list=ls())
ls()
## character(0)
#exercise 9.1
ls("package:methods")###203 items 
##   [1] "addNextMethod"                   "allNames"                       
##   [3] "Arith"                           "as"                             
##   [5] "as<-"                            "asMethodDefinition"             
##   [7] "assignClassDef"                  "assignMethodsMetaData"          
##   [9] "balanceMethodsList"              "body<-"                         
##  [11] "cacheGenericsMetaData"           "cacheMetaData"                  
##  [13] "cacheMethod"                     "callGeneric"                    
##  [15] "callNextMethod"                  "canCoerce"                      
##  [17] "cbind2"                          "checkAtAssignment"              
##  [19] "checkSlotAssignment"             "classesToAM"                    
##  [21] "classLabel"                      "classMetaName"                  
##  [23] "className"                       "coerce"                         
##  [25] "coerce<-"                        "Compare"                        
##  [27] "completeClassDefinition"         "completeExtends"                
##  [29] "completeSubclasses"              "Complex"                        
##  [31] "conformMethod"                   "defaultDumpName"                
##  [33] "defaultPrototype"                "doPrimitiveMethod"              
##  [35] "dumpMethod"                      "dumpMethods"                    
##  [37] "el"                              "el<-"                           
##  [39] "elNamed"                         "elNamed<-"                      
##  [41] "empty.dump"                      "emptyMethodsList"               
##  [43] "evalOnLoad"                      "evalqOnLoad"                    
##  [45] "evalSource"                      "existsFunction"                 
##  [47] "existsMethod"                    "extends"                        
##  [49] "externalRefMethod"               "finalDefaultMethod"             
##  [51] "findClass"                       "findFunction"                   
##  [53] "findMethod"                      "findMethods"                    
##  [55] "findMethodSignatures"            "findUnique"                     
##  [57] "fixPre1.8"                       "formalArgs"                     
##  [59] "functionBody"                    "functionBody<-"                 
##  [61] "generic.skeleton"                "getAllSuperClasses"             
##  [63] "getClass"                        "getClassDef"                    
##  [65] "getClasses"                      "getDataPart"                    
##  [67] "getFunction"                     "getGeneric"                     
##  [69] "getGenerics"                     "getGroup"                       
##  [71] "getGroupMembers"                 "getLoadActions"                 
##  [73] "getMethod"                       "getMethods"                     
##  [75] "getMethodsForDispatch"           "getMethodsMetaData"             
##  [77] "getPackageName"                  "getRefClass"                    
##  [79] "getSlots"                        "getValidity"                    
##  [81] "hasArg"                          "hasLoadAction"                  
##  [83] "hasMethod"                       "hasMethods"                     
##  [85] "implicitGeneric"                 "inheritedSlotNames"             
##  [87] "initFieldArgs"                   "initialize"                     
##  [89] "initRefFields"                   "insertClassMethods"             
##  [91] "insertMethod"                    "insertSource"                   
##  [93] "is"                              "isClass"                        
##  [95] "isClassDef"                      "isClassUnion"                   
##  [97] "isGeneric"                       "isGrammarSymbol"                
##  [99] "isGroup"                         "isRematched"                    
## [101] "isSealedClass"                   "isSealedMethod"                 
## [103] "isVirtualClass"                  "isXS3Class"                     
## [105] "kronecker"                       "languageEl"                     
## [107] "languageEl<-"                    "linearizeMlist"                 
## [109] "listFromMethods"                 "listFromMlist"                  
## [111] "loadMethod"                      "Logic"                          
## [113] "makeClassRepresentation"         "makeExtends"                    
## [115] "makeGeneric"                     "makeMethodsList"                
## [117] "makePrototypeFromClassDef"       "makeStandardGeneric"            
## [119] "matchSignature"                  "Math"                           
## [121] "Math2"                           "mergeMethods"                   
## [123] "metaNameUndo"                    "method.skeleton"                
## [125] "MethodAddCoerce"                 "methodSignatureMatrix"          
## [127] "MethodsList"                     "MethodsListSelect"              
## [129] "methodsPackageMetaName"          "missingArg"                     
## [131] "multipleClasses"                 "new"                            
## [133] "newBasic"                        "newClassRepresentation"         
## [135] "newEmptyObject"                  "Ops"                            
## [137] "packageSlot"                     "packageSlot<-"                  
## [139] "possibleExtends"                 "prohibitGeneric"                
## [141] "promptClass"                     "promptMethods"                  
## [143] "prototype"                       "Quote"                          
## [145] "rbind2"                          "reconcilePropertiesAndPrototype"
## [147] "registerImplicitGenerics"        "rematchDefinition"              
## [149] "removeClass"                     "removeGeneric"                  
## [151] "removeMethod"                    "removeMethods"                  
## [153] "representation"                  "requireMethods"                 
## [155] "resetClass"                      "resetGeneric"                   
## [157] "S3Class"                         "S3Class<-"                      
## [159] "S3Part"                          "S3Part<-"                       
## [161] "sealClass"                       "selectMethod"                   
## [163] "selectSuperClasses"              "setAs"                          
## [165] "setClass"                        "setClassUnion"                  
## [167] "setDataPart"                     "setGeneric"                     
## [169] "setGenericImplicit"              "setGroupGeneric"                
## [171] "setIs"                           "setLoadAction"                  
## [173] "setLoadActions"                  "setMethod"                      
## [175] "setOldClass"                     "setPackageName"                 
## [177] "setPrimitiveMethods"             "setRefClass"                    
## [179] "setReplaceMethod"                "setValidity"                    
## [181] "show"                            "showClass"                      
## [183] "showDefault"                     "showExtends"                    
## [185] "showMethods"                     "showMlist"                      
## [187] "signature"                       "SignatureMethod"                
## [189] "sigToEnv"                        "slot"                           
## [191] "slot<-"                          "slotNames"                      
## [193] "slotsFromS3"                     "substituteDirect"               
## [195] "substituteFunctionArgs"          "Summary"                        
## [197] "superClassDepth"                 "testInheritedMethods"           
## [199] "testVirtual"                     "tryNew"                         
## [201] "unRematchDefinition"             "validObject"                    
## [203] "validSlotNames"
length(ls("package:methods"))
## [1] 203
environment(read.table)
## <environment: namespace:utils>
environment(data)
## <environment: namespace:utils>
environment(matrix)
## <environment: namespace:base>
environment(jpeg)
## <environment: namespace:grDevices>
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"
hey<-"smoothScatter"
hey
## [1] "smoothScatter"
ls("package:graphics")==hey  #correct
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [61] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
## [73] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [85] FALSE FALSE FALSE
# 9.2 Argument Matching
bar <- matrix(data = 1:6, nrow = 3, ncol = 2,
       dimnames = list(c("A", "B", "C"), c("D", "E")))
bar
##   D E
## A 1 4
## B 2 5
## C 3 6
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.4 Mixed
bar<-matrix(1:9,3,3,dim=list(c("A","B","C"),c("D","E","F")))
# 9.2.5 Dot-Dot-Dot: Use of Ellipses
args(data.frame)
## function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, 
##     fix.empty.names = TRUE, stringsAsFactors = FALSE) 
## NULL
args(plot)
## function (x, y, ...) 
## NULL

CHAPTER10

# Exercise 10.2a

mynum <- 3  

if (mynum == 0) {
  result <- "zero"
} else if (mynum == 1) {
  result <- "one"
} else if (mynum == 2) {
  result <- "two"
} else if (mynum == 3) {
  result <- "three"
} else if (mynum == 4) {
  result <- "four"
} else if (mynum == 5) {
  result <- "five"
} else if (mynum == 6) {
  result <- "six"
} else if (mynum == 7) {
  result <- "seven"
} else if (mynum == 8) {
  result <- "eight"
} else if (mynum == 9) {
  result <- "nine"
} else {
  result <- "Invalid number"
}
print(result)
## [1] "three"
mynum<-0

result<-switch(mynum,0,1,2,3,4,5,6,7,8,9)
result
## NULL
mynum<-3
result<-switch(mynum,0,1,2,3,4,5,6,7,8,9)

#b

# I
lowdose<-12.5
meddose <- 25.3
highdose <- 58.1
doselevel <- factor(c("Low","High","High","High","Low","Med",
                      "Med"),levels=c("Low","Med","High"))
doselevel
## [1] Low  High High High Low  Med  Med 
## Levels: Low Med High
if ("High" %in% doselevel){
  
  if(lowdose>=10){
    lowdose<-10
  } else {
    lowdose <-lowdose/2
  }
  
  if(meddose>=26){
    meddose<-26
  }
  
  if(highdose<60){
    highdose<-60
  }else{
    highdose<-highdose*1.5
  }
  dosage<-rep(lowdose, length(doselevel))
  dosage[doselevel=="Med"]<-meddose
  dosage[doselevel=="High"]<-highdose
} else{
  doselevel <- factor(x=doselevel,
                      levels = c("Low","Med"),
                      labels=c("Small","Large"))
  
  
  
  if(lowdose<15&&meddose<35){
    lowdose<-lowdose*2
    meddose<-meddose+highdose
  }
  
  dosage<-rep(lowdose,length(doselevel)) 
  dosage[doselevel=="Large"]<-meddose
  
}
dosage
## [1] 10.0 60.0 60.0 60.0 10.0 25.3 25.3
# II
Lowdose<-12.5
meddose <- 25.3
highdose <- 58.1
doselevel <- factor(c("Low","Low","Low","Med","Low","Med",
                      "Med"),levels=c("Low","Med","High"))


if ("High" %in% doselevel){
  
  if(lowdose>=10){
    lowdose<-10
  } else {
    lowdose <-lowdose/2
  }
  
  if(meddose>=26){
    meddose<-26
  }
  
  if(highdose<60){
    highdose<-60
  }else{
    highdose<-highdose*1.5
  }
  dosage<-rep(lowdose, length(doselevel))
  dosage[doselevel=="Med"]<-meddose
  dosage[doselevel=="High"]<-highdose
} else{
  doselevel <- factor(x=doselevel,
                      levels = c("Low","Med"),
                      labels=c("Small","Large"))
  
  
  
  if(lowdose<15&&meddose<35){
    lowdose<-lowdose*2
    meddose<-meddose+highdose
  }
  
  dosage<-rep(lowdose,length(doselevel)) 
  dosage[doselevel=="Large"]<-meddose
  
}
dosage
## [1] 20.0 20.0 20.0 83.4 20.0 83.4 83.4
doselevel
## [1] Small Small Small Large Small Large Large
## Levels: Small Large
# III
lowdose <- 9
meddose <- 49
highdose <- 61
doselevel <- factor(c("Low","Med","Med"),
                    levels=c("Low","Med","High"))

if ("High" %in% doselevel){
  
  if(lowdose>=10){
    lowdose<-10
  } else {
    lowdose <-lowdose/2
  }
  
  if(meddose>=26){
    meddose<-26
  }
  
  if(highdose<60){
    highdose<-60
  }else{
    highdose<-highdose*1.5
  }
  dosage<-rep(lowdose, length(doselevel))
  dosage[doselevel=="Med"]<-meddose
  dosage[doselevel=="High"]<-highdose
} else{
  doselevel <- factor(x=doselevel,
                      levels = c("Low","Med"),
                      labels=c("Small","Large"))
  
  
  
  if(lowdose<15&&meddose<35){
    lowdose<-lowdose*2
    meddose<-meddose+highdose
  }
  
  dosage<-rep(lowdose,length(doselevel)) 
  dosage[doselevel=="Large"]<-meddose
  
}
dosage
## [1]  9 49 49
doselevel
## [1] Small Large Large
## Levels: Small Large
#iv
lowdose <- 9
meddose <- 49
highdose <- 61
doselevel <- factor(c("Low","High","High","High","Low","Med",
                      "Med"),levels=c("Low","Med","High"))
doselevel
## [1] Low  High High High Low  Med  Med 
## Levels: Low Med High
if ("High" %in% doselevel){
  
  if(lowdose>=10){
    lowdose<-10
  } else {
    lowdose <-lowdose/2
  }
  
  if(meddose>=26){
    meddose<-26
  }
  
  if(highdose<60){
    highdose<-60
  }else{
    highdose<-highdose*1.5
  }
  dosage<-rep(lowdose, length(doselevel))
  dosage[doselevel=="Med"]<-meddose
  dosage[doselevel=="High"]<-highdose
} else{
  doselevel <- factor(x=doselevel,
                      levels = c("Low","Med"),
                      labels=c("Small","Large"))
  
  
  
  if(lowdose<15&&meddose<35){
    lowdose<-lowdose*2
    meddose<-meddose+highdose
  }
  
  dosage<-rep(lowdose,length(doselevel)) 
  dosage[doselevel=="Large"]<-meddose
  
}
dosage
## [1]  4.5 91.5 91.5 91.5  4.5 26.0 26.0
#c

mynum<-3
result<-switch(mynum,0,1,2,3,4,5)
mynum<-0
result<-switch(mynum,0,1,2,3,4,5)

mynum <- 3  # Try with other values like 0, 9, etc.

result <- ifelse(mynum >= 0 & mynum <= 9,
                 switch(mynum + 1,  # switch is 1-indexed
                        "zero", "one", "two", "three", "four",
                        "five", "six", "seven", "eight", "nine"),
                 "Invalid number")

print(result)
## [1] "three"
mynum<-0
result <- ifelse(mynum >= 0 & mynum <= 9,
                 switch(mynum + 1,  # switch is 1-indexed
                        "zero", "one", "two", "three", "four",
                        "five", "six", "seven", "eight", "nine"),
                 "Invalid number")

# 10.2 Coding Loops
for(myitem in 5:7){
  cat("--BRACED AREA BEGINS--\n")
  cat("the current item is",myitem,"\n")
  cat("--BRACED AREA ENDS--\n\n")
}
## --BRACED AREA BEGINS--
## the current item is 5 
## --BRACED AREA ENDS--
## 
## --BRACED AREA BEGINS--
## the current item is 6 
## --BRACED AREA ENDS--
## 
## --BRACED AREA BEGINS--
## the current item is 7 
## --BRACED AREA ENDS--
counter<-0
for(myitem in 5:7){
  counter <- counter+1
  cat("The item in run",counter,"is",myitem,"\n")
}
## The item in run 1 is 5 
## The item in run 2 is 6 
## The item in run 3 is 7
mylist<-list(1:3, "hello", matrix(1:4, 2, 2))
for (i in 1:length(mylist)) {
  item<-mylist[[1]]
  print(paste("Item",i,"is of type",class(item)))
}
## [1] "Item 1 is of type integer"
## [1] "Item 2 is of type integer"
## [1] "Item 3 is of type integer"
#You can also nest loops if one of the items is a matrix:
for(i in 1:length(mylist)){
  item<-mylist[[1]]
  if(is.matrix(item)){
    for (r in 1:nrow(item)) {
      for(c in 1:ncol(item)){
        print(paste("Matrix element[",r,",",c,"]=",item[r,c]))
      }
      
    }
  }
}
mylist
## [[1]]
## [1] 1 2 3
## 
## [[2]]
## [1] "hello"
## 
## [[3]]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
#Looping via Index 
colors <- c("red", "green", "blue")

for (i in 1:length(colors)) {
  print(paste("Color", i, "is", colors[i]))
}
## [1] "Color 1 is red"
## [1] "Color 2 is green"
## [1] "Color 3 is blue"
x<-c("red","green","blue")
for (i in 1:length(x)) {
  print(paste("color", i, "is", x[i]))
}
## [1] "color 1 is red"
## [1] "color 2 is green"
## [1] "color 3 is blue"
myvec <- c(0.4,1.1,0.34,0.55)
for(i in myvec){
  print(2*i) 
}
## [1] 0.8
## [1] 2.2
## [1] 0.68
## [1] 1.1
for(i in 1:length(myvec)){
  print(2*myvec[i])
}
## [1] 0.8
## [1] 2.2
## [1] 0.68
## [1] 1.1
foo <- list(aa=c(3.4,1),bb=matrix(1:4,2,2),cc=matrix(c(T,T,F,T,F,F),3,2),
            dd="string here",ee=matrix(c("red","green","blue","yellow")))
foo
## $aa
## [1] 3.4 1.0
## 
## $bb
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $cc
##       [,1]  [,2]
## [1,]  TRUE  TRUE
## [2,]  TRUE FALSE
## [3,] FALSE FALSE
## 
## $dd
## [1] "string here"
## 
## $ee
##      [,1]    
## [1,] "red"   
## [2,] "green" 
## [3,] "blue"  
## [4,] "yellow"
name<-names(foo)
name
## [1] "aa" "bb" "cc" "dd" "ee"
is.mat<-rep(NA,length(foo))
is.mat
## [1] NA NA NA NA NA
nr<- is.mat
nc <- is.mat
data.type <- is.mat
data.type
## [1] NA NA NA NA NA
for (i in 1:length(foo)) {
  member<-foo[[i]]
  if(is.matrix(member)){
    is.mat[i]<-"Yes"
    nr[i]<-nrow(member)
    nc[i]<-ncol(member)
    data.type[i]<-class(as.vector(member))
  }else{
    is.mat[i]<-'No'
  }
}
bar<-data.frame(name,is.mat,nr,nc,data.type,stringsAsFactors =FALSE)
bar
##   name is.mat nr nc data.type
## 1   aa     No NA NA      <NA>
## 2   bb    Yes  2  2   integer
## 3   cc    Yes  3  2   logical
## 4   dd     No NA NA      <NA>
## 5   ee    Yes  4  1 character
list_of_matrices<-list(mat1=matrix(1:4,2,2),mat2=matrix(5:8,2,2))
for (mat_name in names(list_of_matrices)) {
  mat<-list_of_matrices[[mat_name]]
  cat("Matrix:",mat_name,"\n")
  for (i in 1:nrow(mat)) {
    for (j in 1:ncol(mat)) {
      cat("Element[",i,",",j,"]=",mat[i,j],"\n")
    } 
  }
}
## Matrix: mat1 
## Element[ 1 , 1 ]= 1 
## Element[ 1 , 2 ]= 3 
## Element[ 2 , 1 ]= 2 
## Element[ 2 , 2 ]= 4 
## Matrix: mat2 
## Element[ 1 , 1 ]= 5 
## Element[ 1 , 2 ]= 7 
## Element[ 2 , 1 ]= 6 
## Element[ 2 , 2 ]= 8
# 10.3.2 The repeat Statement
fib.a<-1
fib.b<-1
repeat{
  temp<-fib.a+fib.b
  fib.a<-fib.b
  fib.b<-temp
  cat(fib.b,",",sep = "")
  if(fib.b>150){
    cat("BREAK NOW...\n")
    break
  }
}
## 2,3,5,8,13,21,34,55,89,144,233,BREAK NOW...
#11.1.2 Using return
dummy1<-function(){
  aa<-2.5
  bb<-"string me along"
  cc<-"string 'em up"
  dd<-4:8
}

dummy2<-function(){
  aa<-2.5
  bb<-"string me along"
  cc<-"string 'em up"
  dd<-4:8
  return (dd)
}

foo<-dummy1()
foo
## [1] 4 5 6 7 8
bar <- dummy2()
bar
## [1] 4 5 6 7 8
dummy3<-function(){
  aa<-2.5
  bb<-"string me along"
  return(aa)
  cc<-"string em up"
  dd<-4:8
  return(bb)
}
baz<-dummy3()
baz
## [1] 2.5
# Exercise 11.1
#(a)
myfib4 <- function(thresh,printme){
  if(printme){
    fib.a <- 1
    fib.b <- 1
    cat(fib.a,", ",fib.b,", ",sep="")
    repeat{
      temp <- fib.a+fib.b
      fib.a <- fib.b
      fib.b <- temp
      cat(fib.b,", ",sep="")
      if(fib.b>thresh){
        cat("BREAK NOW...")
        break
      }
    }
  } else {
    fibseq <- c(1,1)
    counter <- 2
    repeat{
      fibseq <- c(fibseq,fibseq[counter-1]+fibseq[counter])
      counter <- counter+1
      if(fibseq[counter]>thresh){
        break
      }
    }
    return(fibseq)
  }
}
myfib4(thresh=150,printme=TRUE)
## 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, BREAK NOW...
myfib4(1000000,T)
## 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, BREAK NOW...
myfib4(150,FALSE)
##  [1]   1   1   2   3   5   8  13  21  34  55  89 144 233
myfib4(1000000,printme=F)
##  [1]       1       1       2       3       5       8      13      21      34
## [10]      55      89     144     233     377     610     987    1597    2584
## [19]    4181    6765   10946   17711   28657   46368   75025  121393  196418
## [28]  317811  514229  832040 1346269
#b
mynum_factorial<-1
while(mynum>1){
  mynum_factorial<-mynum_factorial*mynum
  mynum<-mynum-1
}
mynum_factorial
## [1] 1
myfac<-function(int){
    result<-1
    while(int>1){
      result<-result*int
      int<-int-1
    }
    return(result)
  }
myfac(5)
## [1] 120
myfac(120)
## [1] 6.689503e+198
myfac(0)
## [1] 1
##(ii)
myfac2 <- function(int){
  if(int<0){
    return(NaN)
  }
  result <- 1
  while(int>1){
    result <- result*int
    int <- int-1
  }
  return(result)
}
myfac2(5)
## [1] 120
myfac2(12)
## [1] 479001600
myfac2(0)
## [1] 1
myfac2(-6)
## [1] NaN
#alternative
myfacii<-function(int){
  if(int<0){
    return(NaN)
  }
  result<-1
  counter<-int
  while (counter>1) {
    result<-result*counter
    counter<-counter-1
  }
  return(result)
}

myfac2(5)     
## [1] 120
myfac2(12)    
## [1] 479001600
myfac2(0)    
## [1] 1
myfac2(-6)
## [1] NaN
counter<-1
while (counter<=5) {
  print(paste("This is a loop number", counter))
  counter<-counter+1
}
## [1] "This is a loop number 1"
## [1] "This is a loop number 2"
## [1] "This is a loop number 3"
## [1] "This is a loop number 4"
## [1] "This is a loop number 5"
a<-1
b<-3
add_numbers<-function(a,b){
  result<-a+b
  return(result)
}

myfacm<-function(int){
  result<-1
  while(int>1){
    result<-result*int
    int<-int-1
  }
  result(result)
}

c_to_f<-function(celsius){
  return((celsius*9/5)+32)
}
# Exercise 11.2
Compound_F<-function(P,i,y,t=12,ploitit=TRUE,...){
  times<-1:y
  F<-P*(1+i/(100*t))^(t*times)
  if (ploitit){
plot(times,F,type="S",xlab="Year (y)",ylab="Balanced(F)",main="Compound Interest Calculator", ...)  
  }else{
      return(F)
    }
}

#11.2i
Compound_F(P=5000,i=4.4,y=10,ploitit = FALSE)
##  [1] 5224.491 5459.062 5704.164 5960.271 6227.877 6507.498 6799.674 7104.967
##  [9] 7423.968 7757.291
#11.2ii
Compound_F(P=100,i=22.9,y=20,ploitit=TRUE)
#11.2iii
Compound_F(P=100,i=22.9,y=20,ploitit=TRUE)
annualF<-Compound_F(P=100,i=22.9,y=20,ploitit = FALSE)           
 lines(1:20,annualF,type = "s",col="Pink",lty=3)
 legend("topleft",legend = c('Monthly Interest',"Annually Interest"),col=c("blue","black"),lty=c(1,2))

#11.2B
 Equation<-function(k1,k2,k3){
   if(missing(k1)||missing(k2)||missing(k3)){
     return("One or more of the arguments k1, k2, or k3 is missing")
   }
   D<-k2^2-4*k1 * k3
   if(D<0){
     cat("no real roots.")
     return(numeric(0))
   }else if (D==0){
     return(-k2/(2*k1))
   }else{
     return(c((-k2-D^0.5)/(2*k1),(-k2+D^0.5)/(2*k1)))
   }
 }
 ##(i)
 Equation(k1=2,k2=-1,k3=-5)
## [1] -1.350781  1.850781
 Equation(1,1,1)
## no real roots.
## numeric(0)
 ##(ii)
 Equation(k1=1.3,k2=-8,k3=-3.13)
## [1] -0.3691106  6.5229567
 Equation(2.25,-3,1)
## [1] 0.6666667
 Equation(1.4,-2.2,-5.1)
## [1] -1.278312  2.849740
 Equation(-5,10.11,-9.9)
## no real roots.
## numeric(0)
 ##(iii)
 Equation(0)
## [1] "One or more of the arguments k1, k2, or k3 is missing"
## 11.3 Specialized Functions
# Externally Defined
 multiples_helper_ext <- function(x,matrix.flags,mat){
   indexes <- which(matrix.flags)
   counter <- 0
   result <- list()
   for(i in indexes){
     temp <- x[[i]]
     if(ncol(temp)==nrow(mat)){
       counter <- counter+1
       result[[counter]] <- temp%*%mat
     }
   }
   return(list(result,counter))
 }
 multiples4 <- function(x,mat,str1="no valid matrices",str2=str1){
   matrix.flags <- sapply(x,FUN=is.matrix)
   if(!any(matrix.flags)){
     return(str1)
   }
   helper.call <- multiples_helper_ext(x,matrix.flags,mat)
   result <- helper.call[[1]]
   counter <- helper.call[[2]]
   if(counter==0){
     return(str2)
   } else {
     return(result)
   }
 }
#Part C: Geometric Mean Function for a List
 
  #Create a function geolist() that:
 # Loops through a list.
#If the item is a vector → compute geometric mean.
#If it’s a matrix → compute geometric mean for each row.

geolist <- function(lst) {
  geo_mean <- function(x) {
    prod(x)^(1 / length(x))
  }
  
  for (i in seq_along(lst)) {
    if (is.vector(lst[[i]])) {
      lst[[i]] <- geo_mean(lst[[i]])
    } else if (is.matrix(lst[[i]])) {
      lst[[i]] <- apply(lst[[i]], 1, geo_mean)
    }
  }
  
  return(lst)
}

foo <- list(
  1:3,
  matrix(c(3.3, 3.2, 2.8, 2.1, 4.6, 4.5, 3.1, 9.4), 4, 2),
  matrix(c(3.3, 3.2, 2.8, 2.1, 4.6, 4.5, 3.1, 9.4), 2, 4)
)
geolist(foo)
## [[1]]
## [1] 1.817121
## 
## [[2]]
## [1] 3.896152 3.794733 2.946184 4.442972
## 
## [[3]]
## [1] 3.388035 4.106080
bar <- list(1:9,matrix(1:9, 1, 9),matrix(1:9, 9, 1),matrix(1:9, 3, 3))
geolist(bar)
## [[1]]
## [1] 4.147166
## 
## [[2]]
## [1] 4.147166
## 
## [[3]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[4]]
## [1] 3.036589 4.308869 5.451362