knitr::opts_chunk$set(echo = TRUE)
library(learnr)
tutorial_options(exercise.timelimit = 10, exercise.blanks = "___+")

What are functions?

output <- do_the_thing(input1, input2)

Example functions

Calculating mean of a vector

num_vec <- 1:10
mean(num_vec)

Functions don't need to provide output, or take inputs

save(object_to_save, file = 'data_file')
getwd()

Built-in functions

Mathematical functions

Functions that operate on individual values:


Mathematical functions

Functions that estimate statistics across a set of values:

x <- c(1, 1, 2, 3, 5, 8, 13)

Getting help

?my_function
help(my_function)

Example help documentation

Tips on using functions

round(pi, digits = 2) 

See examples of function being used!

example('round')

The 'combine' function

What are the inputs and outputs?

glengths <- c(4.6, 3000, 580)

Creating functions (the general pattern)

name_of_function <- function(argument1, argument2) {
    *code that does something based on inputs*
    return(some_results)
}

Creating functions (a simple example)

combine_two_numbers <- function(num1, num2) {
  result <- num1 + num2
  return(result)
}

combine_two_numbers(1, 2)

Don't forget to return a result

Making 'optional' inputs

Assign a default value to inputs with = to make them optional

subtract_from_vec <- function(data_vec, subtract_val = 1) {
  new_data_vec <- data_vec - subtract_val
  return(new_data_vec)
}
test_vec <- 1:10
subtract_from_vec(test_vec)
subtract_from_vec(test_vec, subtract_val = 2)

What are packages?

install.packages('tidyverse')
library(tidyverse)

Getting help with packages

help(package = 'lubridate')

Quick note on Bioconductor

install.packages("BiocManager")
BiocManager::install("GenomicRanges")
library(GenomicRanges)

Word of warning about function names

library(lubridate)
library(here)
lubridate::here()
here::here()

Getting more help

Google -> StackOverflow

Key concepts recap

Using functions:

Writing your own functions:

do_a_thing <- function(input_obj, param1) {
  **STUFF**
  return(result)
}

Now for hands-on practice!

Tips for using web site



AshirBorah/cp_bootcamp_r_tutorials documentation built on May 16, 2024, 3:24 p.m.