library(this.path)
setwd(here())
data_grades <- read.table("data/grades.csv",
header = TRUE, sep = ",", stringsAsFactors = FALSE)Session 4
In the last session, we learned how to load data of various sources into R.
Today’s first part will be about how to manipulate data in R. Importantly, we will learn how to
We will work with fictive data set of student grades. We start by downloading the grades.csv file from the training website, setting our working directory and loading the data:
library(this.path)
setwd(here())
data_grades <- read.table("data/grades.csv",
header = TRUE, sep = ",", stringsAsFactors = FALSE)We begin with selecting interesting variables from a data set. For our grades data set, we want to preserve information about ID, Name, and Exam_Score, and drop all other information.
Variables can be selected by name, after which we inspect the first and last three rows in the data set:
Or by variable indexes
data1 <- data_grades[, c(1, 2, 7)]though this is not that convenient unless you know the column numbers of the variables you want to select.
A more convenient alternative is to use the following function:
The objects data, data1 and data2 are all identical so you can use your preferred way of working!
Next, we want to subset the data set, i.e. preserve interesting rows while removing the others.
For the grades data set, we might be interested in information about students in tutorial group 1:
# select tutorial 1 students only
data_tutorial1 <- data_grades[data_grades$Tutorial == 1, ]or alternatively:
data_tutorial1 <- subset(data_grades, Tutorial == 1)Subsetting also works using characters. For instance, to retrieve only information for females:
# select female students only
data_females <- data_grades[data_grades$Gender == 'Female', ]Inspect your new data sets!
Use the grades data set.
Generate a data set that contains information about the student ID, student name, their tutorial group, participation grade and their exam score.
Further reduce the data set obtained under 1 to only display information of students in tutorial group 4.
Further reduce the data set obtained under 2 to only display information of students with an exam score of more than 80. How many such students are there?
Let us continue with further data manipulations. The variable Tutorial is currently an integer:
class(data_grades$Tutorial)[1] "integer"
but it should be a factor (a categorical variable). This can be easily changed in R:
data_grades$Tutorial <- as.factor(data_grades$Tutorial)after which you can inspect its new class:
class(data_grades$Tutorial)[1] "factor"
When inspecting the variable itself, R now mentions the different levels of the factors:
data_grades$Tutorial [1] 2 3 4 2 1 4 3 1 1 3 4 2 4 4 3 1 3 4 1 2 1 1 3 1 3 3 2 3 2 1 4 4 4 2 3 2 2 4
[39] 4 2 1 3
Levels: 1 2 3 4
which you can also directly retreive via:
levels(data_grades$Tutorial)[1] "1" "2" "3" "4"
Sometimes we want to add a variable to an existing data set.
For instance, we want to add the exam score on 10 instead of 100. To add a new variable, use the $ operator and specify a new variable name:
What is the class of the variable Tutor? Transform it into a factor. How many tutors are there?
Add a new variable to compute the final score of each student, which is the weighted average of their participation grade (20%) and their exam score (80%)
Retrieve the final score of the students in tutorial group 2. Obtain summary statistics of their final scores.
What is the lowest and the highest final score in tutorial group 2? Retrieve this information from the summary statistics as well as by using a dedicated function.
To create plots with R’s standard graphics package, there are high-level and low-level plotting functions.
plot(x = long_data$MONTH, y = long_data$TEMP) ## Scatter plot wrt monthNotice that function plot() calls methods.
It will perform different operations depending on the class of the passed object. (We study the lm() function in detail in the next session!)
library(quantmod)
getSymbols("AAPL", src = "yahoo", from = "2024-01-01", to = Sys.Date())AAPL$AAPL.Close
The plot() function takes several many arguments that can change the layout of the plots. See ?par for all graphical options; there are many!
Some examples:
col: color of lines / pointslty, lwd: Line type and thicknesspch: Point type (1-16)main, sub: Title, subtitlexlab, ylab: x and y axis labelslog, xlog and ylog for logarithmic scalesxlim, ylim: x and y axis limits (for overriding R’s default choices)mfcol, mfrow: Multiple plots in one graphics window (column-wise/row-wise)lines: Draw linesabline: Quickly add horizontal, vertical lines, and lines using equation \(y = bx + a\)
points: Add pointsarrows: Add arrowstitle: Add a titlelegend: Add a legendtext: Add text at \((x,y)\) coordinatesmtext: Add text with positional specification like side=1,...,4
We want to visualize the daily temperatures in the climate data specifically for Maastricht. First, make a basic plot of temperatures in Maastricht then customise the plot in the following ways:
The title of the X-axis should say ‘Month’, the title of the Y-axis ‘Average Temperature’.
Make the plot a line plot with a blue line. (Hint: specifying the colour literally as "blue" works)
Make the tick marks appear on the inside of the figure rather than the outside.
Calculate the average temperature.
Add a horizontal line with the average maximum temperature
You will need to consult the help file for this exercise; see this therefore more as an exercise in how to navigate R’s help system, than an exercise in plotting (which we will cover in more detail later).
You may want to ask ChatGPT for help.
You can manually save graphs of several formats.
Best practice is to save a graph through a device such as pdf or similar:
loop that iterates over time points (months).wide_data$MAASTRICHT
xlab = "Time", ylab = "Value", main = "Adding Data Over Time", type = 'l')
# Gradually plot more and more of the data using a `for loop`
for (i in 4:nrow(wide_data)) {
plot(1:i, wide_data$MAASTRICHT[1:i], # notice index i is increasing the number of plotted points
xlab = "Time", ylab = "Value", main = "Adding Data Over Time", type = 'l')
}?ylim, ?Sys.sleep
ggplot2 (see book by Hadley Wickham), plotly, Rgnuplot,…?ggplot2::geom_line?ggplot # a bit complicated help file
help(package = "ggplot2") # a nicer list of all layer functions, see 'geom_line'+ for layerswide_data is a data frame with an indexgeom_line (line plot)color is defined in aes below compared to the earlier slide.ggplot2::geom_line.load("data/climate_wide.Rdata") # load data
wide_data$index <- 1:nrow(wide_data) # create data frame
ggplot(wide_data, aes(x = index, y = MAASTRICHT)) +
geom_line(color = "blue", size = 1, linewidth = 2) +
geom_line(aes(x = index, y = EINDHOVEN), linewidth = 0.3) # Adds Eindhoven data to the last plotload("data/climate_wide.Rdata") # load data
wide_data$index <- 1:nrow(wide_data) # create data frame
ggplot(wide_data, aes(x = index, y = MAASTRICHT)) +
geom_line(color = "blue", size = 1, linewidth = 2) +
geom_line(aes(x = index, y = EINDHOVEN), linewidth = 0.3) + # Adds Eindhoven data to the last plot
labs(
x = "X Axis", y = "Y Axis", color = "Legend Title", # Axis labels and legend title
title = "Line Plot with Two Variables"
) +
scale_color_manual(values = c("blue", "red")) + # Custom colors
theme_minimal() # Minimal theme for a clean lookgeom_point, geom_hline, labs.