RStudio project setup

  1. Start by opening RStudio and create a new project

Functions

  1. Print function
    Let’s start by writing a function that will print its one argument (e.g. 2).
myprint <- function(x) {
    print(x)
}
myprint(2)
## [1] 2
  1. Default arguments Let’s now add a default value to this function’s argument
myprint()
## Error in print(x): argument "x" is missing, with no default
myprint_def <- function(x = "no name") {
    print(x)
}
myprint_def()
## [1] "no name"

Control structures

  1. for loop
    Now consider the following data.frame:
first_name last_name gender
Hermione Granger female
Ron Weasley male
Harry Potter male

Write a function that takes such a data.frame as a argument and that will print the last name for each row.

print_last_name <- function(x) {
    for (i in 1:nrow(x)) {
        print(as.character(x[i, "last_name"]))
    }
}
print_last_name(hp_df)
## [1] "Granger"
## [1] "Weasley"
## [1] "Potter"
  1. while statement Now write the same function using a while statement.
print_last_name_while <- function(x) {
    i <- 1
    while (i <= nrow(x)) {
        print(as.character(x[i, "last_name"]))
        i <- i + 1
    }
}
print_last_name_while(hp_df)
## [1] "Granger"
## [1] "Weasley"
## [1] "Potter"
  1. if/else statetement
    Finally, write a function that will print the last name for females and the first name for males
print_last_name_if <- function(x) {
    for (i in 1:nrow(x)) {
        if (x[i, "gender"] == "female") {
            print(as.character(x[i, "last_name"]))
        } else if (x[i, "gender"] == "male") {
            print(as.character(x[i, "first_name"]))
        }
        
    }
}
print_last_name_if(hp_df)
## [1] "Granger"
## [1] "Ron"
## [1] "Harry"

There are only two hard things in Computer Science:

  • cache invalidation, and
  • naming things.

– Phil Karlton