R Part 4 - Coding: Conditionals, loops, Graphing

Dave White

Conditionals

name="DNW"

if (name == "DNW") {
  fist="David"
  last="White"
} else if (name=="JLB") {
  first="Justin"
  last="Benson"
} else {
  first=NA
  last=NA
}
print(frsit)

x <- -3

if (x < 0) {
  print("x is negative ")
} else if (x> 0) {
  print ("x is positive")
} else if (x == 0) {
  print ("x is positive")
} else {
  print("x is invalid")
}

Combined logic

x='a'

if (x == "a" || x=="A") {
  y=1
} else if (x=="B" || x=="b") {
  y=2
} else {
  y=3
}
print(y)

Double vs Single

Use '&' and '|' for bare logical statements
Use '&&' and '||' in conditional statements
(Latter uses short-circuit evaluation)

switch

switch(x,
first = 1,
second = 2,
third = 3,
fourth = 4,
fifth = 5,
sixth = 6,
NA
)

Loops

The Problem

print(10)
Sys.sleep(1)
print(9)
Sys.sleep(1)
print(8)
Sys.sleep(1)
print(7)
# ...
disp(10)
Sys.sleep(1)

The Solution

for (val in 1:10) {
    print(val)
    Sys.sleep(1)
}

x=1:10
for (val in x) {
    print(val)
    Sys.sleep(1)
}

Looping

last=0;
my.matrix <- matrix(1,3,4)
for (row in 1:nrow(my.matrix)){
    for (col in 1:ncol(my.matrix)){
        my.matrix[row,col]=3+last
        last=my.matrix[row,col]
    }
}

print(my.matrix)
cat(my.matrix,sep="\n")

while loop

x=10
while (x > 0) {
    print(x)
    Sys.sleep(1)
    x <- x-1
}

repeat

i<-1
repeat {
  i<-i+1
  Sys.sleep(1)
  print(i)
}

hit esc key to cancel execution

Graphing

https://www.r-graph-gallery.com/

plot

plot(1,1)
plot(c(1, 10), c(20, 30))
x=1:10
y=20:30
plot(x,y)
plot(x,y, type='l')
plot(x,y, type='l', col='red')
plot(x,y, type='l', col='red', cex=1.5, pch=1)
plot(x,y, type='l', col='red', cex=1.5, pch=2)
plot(x,y, type='l', col='red', cex=1.5, pch=2, lwd=2)
plot(x,y, type='l', col='red', cex=1.5, pch=2, lty=3)
plot(x,y,
     type='l', col='red', cex=1.5, pch=2, lty=3,
     main="My Plot", xlab="x values (au)", ylab="y values (au)")

#multiple
lines(c(1, 10), c(20, 30))
points(c(2.5, 3.5), c(3.5, 3.5))

#legend
my.labels=c("data1","data2")
my.colors=c("black","red")
legend("topright", my.labels, fill=my.colors)

pie

my.counts=c(15,50,35,40)
pie(my.counts)
pie(my.counts, init.angle=45)

my.labels=c("test1","test2","test3")
my.colors=c("blue","red","black","violet")
pie(my.counts,
    main="Test scores", label=my.labels, col=my.colors)

# legend
legend("topright", my.labels, fill=my.colors

bar

x <- c("A", "B", "C", "D")

y <- c(2, 4, 6, 8)
barplot(y, names.arg = x)

col
density
width
horiz=True