Coding basics

2024-09-05

1 Week 1

Packages in R

A container for:

  • functions
  • data
  • documentation

{tidyverse} is a metapackage—or a package that loads a set of other packages.

Installing packages

Use install.packages() to install a package from CRAN (Comprehensive R Archive Network):

install.packages("sf")
Error in contrib.url(repos, "source"): trying to use CRAN without setting a mirror

But, remember, this does not work:

install.packages(sf)
Error: object 'sf' not found

Loading packages

Use library() to load a package into your environment:

library(sf)

Why can we use both library(sf) and library("sf")?

The package argument can be the name of a package: as a name, literal character string, or a character string.

base functions and packages are always available

The {base} package for R is one of fifteen “base packages” that are always available. Functions like sum(), max(), and paste0() are all examples of “base functions”.

Functions in R

Functions take inputs (known as arguments or parameters) and return outputs.

A container for:

  • Logic (a.k.a. an algorithm)
  • Math
  • More functions
  • Data or connections to data sources

Some functions require a specific type of input:

sum(1, 2, 3)
[1] 6
sum("A", "B", "C")
Error in sum("A", "B", "C"): invalid 'type' (character) of argument

But some functions are more flexible:

paste0(1, 2, 3)
[1] "123"
paste0("A", "B", "C")
[1] "ABC"

Order of execution matters!

var <- 0
var + 2
[1] 2
var <- 1
var
[1] 1
var <- 0
var <- 1
var + 2
[1] 3
var
[1] 1