knitr::opts_chunk$set(echo = TRUE)

Loops (ways to automate repetition)

# Make a loop do something 3 times
# 1:3 creates a vector with 3 numbers in it, 9,10,11
# the loop will run 3 times, because there are three things to assign to i
for(i in 1:3){
  print("orchid")
}

# show the value of i each step of the loop
for(i in 1:3){
  print(i)
}

# index does not have to be numbers
flowers <- c("daisy","bluebell","petunia","lilly")
for(i in flowers){
  print(i)
}

example of a function

pow <- function(x,y) {
  # function to print x raised to the power y
  result <- x^y
  print(paste(x,"raised to the power", y, "is", result))
}

pow(11,11)

Example of a sum function

my_sum <- function(x) {
  sum <- 0
  for(i in x) sum <- sum + i
  return(sum)
}

my_sum(1:666)

#

Creates a sequence of numbers -> 1:5 & #seq(from, to)

1:5
seq(from = 1, to = 5)


npalmer11/psyc7709 documentation built on June 3, 2022, 7:04 a.m.