R brush-up

Author

Boris Hejblum

Published

June 6, 2024

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).
Code
myprint <- function(x) {
    print(x)
}
Code
myprint(2)
[1] 2
  1. Default arguments Let’s now add a default value to this function’s argument
Code
myprint()
Error in myprint(): argument "x" is missing, with no default
Code
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.

Code
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.
Code
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 statement
    Finally, write a function that will print the last name for females and the first name for males.
Code
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