Week 01 - Workshop

Load tidyverse

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Functions

A function is an action that we tell R to perform. You have already seen some in action. R already knows the names of thousands of different functions (later on, you can learn to write your own). We can use functions to calculate means, plot graphs, run statistical tests and many more useful things. To use a function, you need to type the name of the function followed by open brackets. Inside the open brackets you put whatever you want R to perform the action on, in this format:

a_function(….)
name_of_the_function(what_the_function_acts_on)

For example, the command below tells R to use the printfunction to return the phrase, (“Hi, welcome to BEM2031 Week 1 workshop”)

print("Hi, welcome to BEM2031 Week 1 workshop")
## [1] "Hi, welcome to BEM2031 Week 1 workshop"

Arguments refers to the information included in the brackets after a function, which the function acts on. When we have multiple arguments, we separate them using commas. For example, the sum function adds together the arguments in brackets:

sum(1,4,12,8)
## [1] 25

This is the same as:

1 + 4 + 12 + 8
## [1] 25

In the code chunk, use the sqrt function to find the square root of 135.

sqrt(135)
## [1] 11.61895

Objects

Objects are items that we create and store in R’s memory. First we need to name it (using alphanumeric characters, full stops, and underscores), then we can use an ‘arrow’ assignment operator to assign whatever we want to store inside the object of that name.

an_object <- …
name_of_the_object <- what_the_object_will_contain

For example, we might create an object called ‘x’, that contains the number 100.

x <- 100

When you successfully create an object in R, it won’t return anything on the command line.

This just means that R has done what you’ve instructed and stored the object, awaiting further instructions. You will see the object pop up in the environment window in the top right corner – this screen is very useful for keeping track of every object you have created and saved during an R session. ‘x’ is now available for use.

For example:

x / 2
## [1] 50

Putting it all together

Most commands in R use functions, objects, and arguments together, as follows:

an_object <- a_function(argument_1, argument_2…)
name_of_object <- name_of_function(arguments_for_function_to_act_on)

y <- sum(1,3,6,7,3333)

Tips:

· To cycle through previous commands that you have entered during an R session, click on the command line and use the up and down arrows on your keyboard

· If R returns a plus sign, it means you have not finished your command (e.g. you have missed off the last bracket). You can either enter the rest of your command, or press escape to cancel and start again

· R is case sensitive and very fussy – you need to type in the command exactly right for it to work (keep an eye on brackets and commas especially which are easy to get wrong)

Using what you have learned, create a new object called “total_output” that sums the numbers 123, 456, and 789. Use the name of the object to find the result.

total_output <- sum(123, 456, 789)
total_output
## [1] 1368

Fix the following code:

z <- Sum(1,2,3) sum(1,2,45,) z -> 2000 z <- sum[1,3,5,99] z!_total <- 1000 1_total <- 343

z <- sum(1,2,3)
sum(1,2,45)
## [1] 48
z <- 2000
z <- sum(1,3,5,99)
z_total <- 1000
total_1 <- 343

Looking at more data

We will use a built in dataset called mpg. You can go to Help and search for mpg to learn more about the data.

First, use the head function to quickly look at the first few rows of data, and the column headers.

head(mpg)
## # A tibble: 6 × 11
##   manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class 
##   <chr>        <chr> <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr> 
## 1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compa…
## 2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compa…
## 3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compa…
## 4 audi         a4      2    2008     4 auto(av)   f        21    30 p     compa…
## 5 audi         a4      2.8  1999     6 auto(l5)   f        16    26 p     compa…
## 6 audi         a4      2.8  1999     6 manual(m5) f        18    26 p     compa…

Let’s summarise the data:

summary(mpg)
##  manufacturer          model               displ            year     
##  Length:234         Length:234         Min.   :1.600   Min.   :1999  
##  Class :character   Class :character   1st Qu.:2.400   1st Qu.:1999  
##  Mode  :character   Mode  :character   Median :3.300   Median :2004  
##                                        Mean   :3.472   Mean   :2004  
##                                        3rd Qu.:4.600   3rd Qu.:2008  
##                                        Max.   :7.000   Max.   :2008  
##       cyl           trans               drv                 cty       
##  Min.   :4.000   Length:234         Length:234         Min.   : 9.00  
##  1st Qu.:4.000   Class :character   Class :character   1st Qu.:14.00  
##  Median :6.000   Mode  :character   Mode  :character   Median :17.00  
##  Mean   :5.889                                         Mean   :16.86  
##  3rd Qu.:8.000                                         3rd Qu.:19.00  
##  Max.   :8.000                                         Max.   :35.00  
##       hwy             fl               class          
##  Min.   :12.00   Length:234         Length:234        
##  1st Qu.:18.00   Class :character   Class :character  
##  Median :24.00   Mode  :character   Mode  :character  
##  Mean   :23.44                                        
##  3rd Qu.:27.00                                        
##  Max.   :44.00

We can look at column names by themselves:

colnames(mpg)
##  [1] "manufacturer" "model"        "displ"        "year"         "cyl"         
##  [6] "trans"        "drv"          "cty"          "hwy"          "fl"          
## [11] "class"

Note that mpg has not been loaded into our environment. If we want to load it in, we need to assign it to an object. We will assign it to the same name.

mpg <- mpg

How many rows and columns are there? What data types are there in the dataset? Do they make sense?

Variable types

Different types of data produces different types of variables. One of the most important distinctions is between continuous and categorical data.

Categorical variables classify data into mutually exclusive categories. For example, the answer to the question “Have you done any coding before” is YES or NO. Categorical variables have no inherent numerical meaning. For example, I might assign 1 to YES and 2 to NO, or the other way round. Categorical variables may be nominal or ordinal; ordinal variables can be ranked in some logical order, while nominal variables can not.

Can you find an example of each in the mpg dataset?

Continuous variables do have an inherent numerical meaning and can be measured on a continuous scale.

Can you find an example of a continuous variable in the mpg dataset?

More plotting

Similar to our previous plot, we can use a scatterplot (geom_point) to visualise the relationship between fuel efficiency on the highway and engine displacement for each car.

To create this scatterplot, we need to specify:

x-axis: Engine displacement
y-axis: Highway fuel efficiency"

What do we see?

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy))

We can add extra information to our scatterplot by coloring the points according to cty, which represents fuel efficiency in the city.

Note:

American spelling is used for "color" in ggplot2.
ggplot2 has automatically detected that `cty` is a continuous variable and has assigned a continuous color scale (e.g., a gradient) to represent the different `cty` values.

Can you identify any patterns in the plot?

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy, color = cty))

Let’s try changing the colour by the class variable.

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy, color = class))

What do you see in the plots? What patterns do you see?

What happens when you change colour to ‘model’? What about ‘year’ or ‘cyl’? Is this what you would expect to see?

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy, color = model))

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy, color = year))