Programming

Ranae Dietzel & Andee Kaplan

Hone your programming skillz

If/else statements

Structure:

if(condition) {
  #code to run if condition is true
} else if(second condition) {
  #other code to run if second true
} else {
  #finally, code to run if conditions false
}

Example:

x <- "hello"
if (!is.numeric(x)) {
    print("Numeric input is required")
} else {
  print(TRUE)
}
## [1] "Numeric input is required"

Loops

For loops

for(i in 1:2){
  print(i)  
}
## [1] 1
## [1] 2
library(ggplot2)
cols <- colnames(diamonds)
for(i in cols) {
  print(paste(i, ":", class(diamonds[, i])))
}
## [1] "carat : numeric"
## [1] "cut : ordered" "cut : factor" 
## [1] "color : ordered" "color : factor" 
## [1] "clarity : ordered" "clarity : factor" 
## [1] "depth : numeric"
## [1] "table : numeric"
## [1] "price : integer"
## [1] "x : numeric"
## [1] "y : numeric"
## [1] "z : numeric"

While loops

i <- 1
while (i <= 5) {
  print(i)
  i <- i + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

Write your own functions!

Example function

foo <- function(params) {
  #code goes here
  return(output)
}

Hello, world!

foo <- function(n = 10) {
  stopifnot(n > 0)
  for(i in 1:n){
    print("Hello, world \n")
  }
}
foo(3)
## [1] "Hello, world \n"
## [1] "Hello, world \n"
## [1] "Hello, world \n"

Your turn

  1. Write a function to compute the mean of an input vector.
  2. Add error checking to ensure the input vector is numeric or logical, display an error if not satisfied (see “stop”). If your data is logical, convert it to numeric.
  3. Add a parameter to allow the user to specify if they want to exclude NA values.
  4. Loop over the columns of the diamonds data set and apply your function to all of the numeric columns.
  5. Make a list of other potential problems with a mean function, and potential solutions.