For loops in R

The basic structure of a for() loop in R is …

for(){}
for(i in ...){}

i takes on the values from 1 to 10

for(i in 1:10){}
numbers.1to10 <- 1:10

i <-1
i <-2
for(i in 1:10){
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
#initailize 
x <- 10

for(i in 1:10){
  x <- x + i
  print(x)
}
## [1] 11
## [1] 13
## [1] 16
## [1] 20
## [1] 25
## [1] 31
## [1] 38
## [1] 46
## [1] 55
## [1] 65

A broken for loop

(mayb enot a great example)

# "sequence is not defined
# properly"

# for(z in z:10){
#   print(z^2)
# }
# 
# 
# for(z in 1:10){
#   print(z^2)
# }

is.na()

x <- c(10, NA, 40, 50, NA)
is.na(x)
## [1] FALSE  TRUE FALSE FALSE  TRUE
any(is.na(x) == FALSE)
## [1] TRUE

vectorized notation

#          00   01  02  03  04              
wolves <- c(10, 11, 16, 13, 14)
#00  01  02  03  04
#10, 11, 16, 13, 14
#   /  /    /   /
#10, 11, 16, 13, 14

11/10
## [1] 1.1
# 2001, 11 wolves
wolves[2]
## [1] 11
# 2000
wolves[1]
## [1] 10
11/10
## [1] 1.1
16/11
## [1] 1.454545
13/16
## [1] 0.8125
wolves[2]/wolves[1]
## [1] 1.1
wolves[-1]/wolves[-5]
## [1] 1.100000 1.454545 0.812500 1.076923
# for(i in 1:length(wolves)){
#   
# }

wolves[-1]/wolves[-length(wolves)]
## [1] 1.100000 1.454545 0.812500 1.076923

Drawing things “randomly out of a hat”

d6 <- 1:6
sample(x = d6, 
       size = 2, # sample size
       replace = TRUE)
## [1] 5 6

Alternative splicing

exons <- c("e1","e2","e3")

sample(x = exons, 
       size = 3, # sample size
       replace = FALSE)
## [1] "e2" "e3" "e1"
exons <- c("e1","e2","e3")

e1

exons <- c("e2","e3")

e3

exons <- c("e2")

e2
deck.of.card <- c(....)
sample(x = deck.of.card, size = 1, replace = TRUE)
sample(x = wolves, size = 1, replace = TRUE)
DNA <- c("A","T","C","G")
sample(x = DNA, size = 10, replace = TRUE)
##  [1] "T" "G" "G" "T" "C" "G" "C" "A" "G" "T"
wolves <- c(10, 12, 15, 16, 17, 14, 16, 18, 12, 11)
elk    <- c(100,112,150,160,107,104,116,108,112,90)
year   <- c(2000:2009)

plot(wolves ~ year, 
     type = "l",
     xlim = c(2000,2009),
     ylim = c(0, 200))

plot(wolves ~ year, 
     type = "b",
     xlim = c(2000, 2009),
     ylim = c(0, 200))
points(elk ~ year, 
       type = "b")

plot(wolves , year, type = "b")
plot(x = wolves , y = year, type = "b")

plot(year , wolves, type = "b")


plot(y = wolves , x = year, type = "b")

points(elk ~ year, type = "b")

dimensionality dimensions 3 to 10

dim <- 3:10
for(i in 1:length(dim)){
  # fancy physic stuff
}
d <- c(3,4,5,6,7,8,9,10)
d <- 3:10
d <- c(3:10)
d <- seq(3,10)
d <- seq(3,10,1)
d <- seq(from = 3,to = 10)
d <- seq(from = 3,to = 10, by = 1)