Functions, loops and conditional statements

ANU BDSI
workshop
Introduction to R programming

Emi Tanaka

Biological Data Science Institute

3rd April 2024

Current learning objective

  • -Conduct elementary arithmetic operations using R
  • -Navigate the RStudio interactive development environment (IDE)
  • -Install external packages in R to extend functionality
  • -Comprehend various object types in R
  • -Manipulate lists, matrices, and vectors in R
  • -Compute basic summary statistics including mean, median, quartiles, and standard deviation using R
  • -Grasp the concept of missing values within the R environment
  • -Import and export data in R
  • Create basic functions, employ conditional statements, and utilize for loops in R
  • Decipher error messages and do basic troubleshooting


The content in this slide will be hard for those new to programming!

Don’t give up!

Functions

  • A function in R has three parts:
    • formals(): the list of input arguments,
    • body(): the code inside the function,
    • environment(): the environment (out of scope for this workshop).
  • Writing your own functions can make repetitive tasks easier.
  • You can make a new function using function().

Examining functions

  • Writing the name of the function without arguments shows the internal code:

Conditional statements

  • The condition in the if statement needs to evaluate to a single TRUE or FALSE
  • ifelse() is the vectorised version of if() and else statement.

Example

Loops

Basic troubleshooting

  • Whether you are good at programming or not, you will inevitably encounter errors.

  • If you encounter an error,

    1. Read the error message!
    2. Google the error message or ask generative AI (like chatGPT)
    3. Ask for help with a reproducible example

Reproducible Example with reprex LIVE DEMO

  • Copy your minimum reproducible example then run
reprex::reprex(venue = "slack")

Asking for help

  • How about the question on the right?
  • What makes it hard or easy for people to answer this question?

Checklist (note: not an exhaustive checklist)

If the question is asked in an public forum or similar:

If the problem is computer system related

If the problem is based on data

Summary

  • Write new functions using function().
  • Use if, else, and ifelse for conditional statements.
  • Use for loops for repetitive tasks.
  • Troubleshoot errors by reading the error message and asking for help with a reproducible example.
  • Reproducible examples can be generated using the reprex package.

Exercise time

10:00