R Coding Basics

Sarah Cassie Burnett

September 2, 2025

Running R and RStudio Locally


  • You should have installed R and RStudio on your local machine.
  • Visit Posit to download R and RStudio.
  • If you are having issues with installing it locally, use a sandbox to run R in class today. Go to office hours to get this set up this week.
  • Have Quarto downloaded for the first assignment (to be posted).

  • Output showing differently from mine? Check your version of R in the Console:
R.version.string
[1] "R version 4.5.1 (2025-06-13)"

Scan and fill out for participation credit https://forms.gle/AicqDBeY4bfmEK578

Annoucements

  • Online Week 2 quiz posted at the end of class.
  • In class quiz on Thursday.
  • Coding Assignment 1 to be posted Tuesday/Wednesday to be due next Tuesday 11:59 pm.

Scan and fill out for participation credit https://forms.gle/AicqDBeY4bfmEK578

R Programming Basics

What Can R Do?


  • R is a powerful language for data analysis and visualization
  • It is also a general-purpose programming language
  • Does everything from web development to machine learning
  • It is open-source and has a large community of users and developers

Variables in R

  • Defining (or assigning) a variable means giving a name to a value to an R object so you can reuse it later.
  • Use <- to assign to.
  • Variable names:
    • Can contain: letters, numbers, _, .
    • Cannot start with a number or _
    • Case-sensitive

R can do calculations


  • R can be used as a simple calculator
  • You can perform arithmetic operations on numbers
# Addi a number and store it to a value
sum_of_2plus2 <- 2 + 2


sum_of_2plus2
[1] 4

Some Common Arithmetic Operators


  • + addition
  • - subtraction
  • * multiplication
  • / division
  • ^ exponentiation (also **)

Try it out!


  • Calculate the cost to see your favorite artist as soon as you possible could.
  • Look up flights, night(s) in hotel, per diem.
  • Use the R console to put together the budget.
05:00

Some Common Boolean / Logical Operators


  • == equal to
  • != not equal to
  • <, >, <=, >= comparisons
  • & AND, | OR , ! NOT
5 == 5     # TRUE
5 != 3     # TRUE
4 < 2      # FALSE
10 >= 7    # TRUE

Objects

What is an Object?

  • An object in R can be a data structure used to store data.
  • It can vary from simple scalar types to more complex containers like vectors, lists, or data frames.
  • Objects hold not only data but also information about the type of data and the operations that can be performed on them.
  • Every entity in R is considered an object, making R a language based around the manipulation of objects.

How to Store Data

  • In R, you can store data in objects using the assignment operator <-.
  • The object name is on the left of <-, and the data or value you wish to assign to the object is on the right.
  • Then you can print the object to the console using the object name.
# Store the value 42 in the object my_number
my_number <- 42

# Print the value of my_number
my_number 
[1] 42

Storing a Vector


  • Sometimes you want to store more than one number.
  • In this case you can store a vector.
  • A vector is a collection of numbers or characters.
my_numbers <- c(1, 2, 3, 4, 5)

my_numbers
[1] 1 2 3 4 5

“Printing” objects


  • Sometimes you will see print() used to display the contents of objects.
  • This is not typically necessary.
  • Sometimes you need it (like when printing inside of a function).
  • But usually you can just type the name of the object in the console.

Arithmetic with Vectors


  • Arithmetic in R is vectorized: the operation is applied to each element.
  • With a number (scalar), the operation is repeated for all elements.
  • With two vectors:
    • If they are the same length, operations happen element by element.
    • If they are of different lengths, R will recycle the shorter one
3 * c(1, 2, 3, 4)                           # 3  6  9 12
c(1, 2, 3, 4) + c(10, 20)                   # 11 22 13 24
c(1, 2, 3, 4) + c(10, 20, 30)               # Warning

c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE) # TRUE FALSE FALSE

Your Turn!


  • Store a number in an object
  • Create a vector of numbers and store it in an object
  • “Print” the objects by typing the object names
05:00

Functions

Functions

  • A function is a set of instructions that produces some output.
  • Like in math, a function can take an input (an argument), and it can return a variable.
  • There are built-in, external functions to perform specific tasks.
  • For example, you can use the mean() function to calculate the average of a set of numbers.
  • To do this you have to use the combine function c() to create a vector of numbers.

Function Defaults


  • Many R functions have default argument values.
  • If you don’t specify them, R uses the defaults.
  • You can override defaults by naming the argument.
  • Arguments can be given in any order if you use their names.
  • Let’s look at sample().

Function Resolution


  • In R, functions can be nested.
  • R evaluates them from the innermost call to outward.
  • The result of the inner function becomes the input to the outer one.
input <- 100
output <- sqrt(log(input))     
# log(input) happens first, then sqrt(...)

# Pipe alternative (if using R 4.1+):
output <- input |> log() |> sqrt()

library(tidyverse)
output <- input %>% log() %>% sqrt()

Some Common Base R Functions

  • mean() calculates the mean of a set of numbers.
  • median() calculates the median of a set of numbers.
  • sd() calculates the standard deviation of a set of numbers.
  • sum() calculates the sum of a set of numbers.
  • length() calculates the length of a vector
  • max() and min() calculate the maximum and minimum values of a vector
  • round() rounds a number to a specified number of decimal places
  • sqrt() calculates the square root of a number
  • log() calculates the natural logarithm of a number
  • exp() calculates the exponential of a number
  • abs() calculates the absolute value of a number

Try it out!


Check the built-in R math formulas behave as expected:

  • Create a vector of numbers
  • Store it as a variable
  • Take the exp() of the vector and then take the log() of that
  • Does this formula hold true: \[ \log(e^b) = b \] Try it with a sample of numbers
05:00

Indexing in R


  • Use indexing to extract a subset of your container
  • You can access elements of a vector in several ways:
    • By position
    • By negative index
    • By boolean/logical expressions
    • By name

Packages

From Functions to Packages


  • A function is a set of instructions
    • read_csv() is a function
    • sample() is a function
  • A package is a collection of functions
    • readr is a package that contains the read_csv() function
    • ggplot2 is a package that contains the ggplot() function
  • Use install.packages() to install packages
  • Use library() to load packages
  • You can install packages from CRAN

Installing Packages


  • You can install packages from CRAN (Comprehensive R Archive Network)
  • Another way to install packages is from a GitHub repository
  • We will use the pak package to install packages from GitHub
  • To install pak, run install.packages("pak")

Installing Packages


  • You only need to install a package once
  • After you install a package, you can load it with the library() function
  • Do not put install.packages() in your R script or Quarto document

Try it out!


  • Install the tidyverse package in your environment
  • Load the tidyverse package
  • Install the pak package
05:00