Lecture 2: R Data Importation & Visualization

Basic Arithmetic

This section assigns numeric values to variables and uses R to perform basic arithmetic. The addition and multiplication operators show how R evaluates expressions using stored values.

############################################
###### Assigning values to variables #######
############################################

x <- 5       # Storing 5 in x
y <- 3.14    # Storing 3.14 in y

x + y        # Add the values
## [1] 8.14
x * y        # Multiply the values
## [1] 15.7

Creating Data Frames

A data frame organizes related information into rows and columns, similar to a spreadsheet. In this example, three vectors store employee names, ages, and salaries; these vectors can then be combined into one data frame.

# Create vectors for names, ages, and salaries
names <- c("Grace", "Bibi", "Lisa", "Kelvin", "Akash")
ages <- c(25, 30, 22, 26, 29)
salaries <- c(200000, 250000, 280000, 210000, 300000)

The vectors contain five observations, with each employee’s name, age, and salary in the corresponding position. Keeping the vectors the same length allows them to be combined correctly into a data frame.

# Create vectors for names, ages, and salaries
names <- c("Grace", "Bibi", "Lisa", "Kelvin", "Akash")
ages <- c(25, 30, 22, 26, 29)
salaries <- c(200000, 250000, 280000, 210000, 300000)

employee_data <- data.frame(names, ages, salaries)

# Display summary statistics for each column
summary(employee_data)
##        names        ages         salaries     
##  Length   :5   Min.   :22.0   Min.   :200000  
##  N.unique :5   1st Qu.:25.0   1st Qu.:210000  
##  N.blank  :0   Median :26.0   Median :250000  
##  Min.nchar:4   Mean   :26.4   Mean   :248000  
##  Max.nchar:6   3rd Qu.:29.0   3rd Qu.:280000  
##                Max.   :30.0   Max.   :300000

Measures of Central Tendency

Measures of central tendency describe the centre of a set of values. The mean is the arithmetic average, while the median is the middle value when the observations are ordered.

# Mean and median salaries
mean(employee_data$salaries)
## [1] 248000
median(employee_data$salaries)
## [1] 250000

Sub-setting

Sub-setting selects only the rows or columns that meet a condition. Here, the code creates a new data frame containing employees whose salaries are greater than 250,000.

high_earners <- employee_data[employee_data$salaries > 250000, ]
high_earners
##   names ages salaries
## 3  Lisa   22   280000
## 5 Akash   29   300000

Visualization with ggplot2: Scatter Plot

A scatter plot is used to examine the relationship between two numeric variables. This plot compares employee ages with salaries, with each point representing one employee.

library(ggplot2)

scatter_plot <- ggplot(data = employee_data,
                       aes(x = ages, y = salaries)) +
  geom_point() +
  labs(title = "Ages vs Salaries",
       subtitle = "MOA Staff",
       x = "Age",
       y = "Salary") +
  theme_classic()

scatter_plot

Creating a Bar Plot

A bar plot compares values across categories. This example displays each employee’s salary, making it easier to compare salaries between employees.

bar_plot <- ggplot(data = employee_data,
                   aes(x = names, y = salaries)) +
  geom_bar(stat = "identity") +
  labs(title = "Salaries by Employee",
       subtitle = "MOA Staff",
       x = "Employee",
       y = "Salary") +
  theme_classic()

bar_plot

Handling Missing Data

Missing values are represented by NA in R. The is.na() function identifies missing entries, and na.rm = TRUE tells mean() to ignore missing values when calculating the average.

# Create a vector with missing values
ages_with_na <- c(25, 30, NA, 22, NA, 28)

# Check for missing values
is.na(ages_with_na) # TRUE where values are missing
## [1] FALSE FALSE  TRUE FALSE  TRUE FALSE
# Calculate the mean while ignoring missing values
mean(ages_with_na, na.rm = TRUE)
## [1] 26.25

Creating Functions

A function is a reusable block of code that performs a task. This function accepts a rectangle’s length and width, multiplies them, and returns the area.

# Define a function to calculate the area of a rectangle
area_rectangle <- function(length, width) {
  return(length * width)
}

# Call the function with length 5 and width 3
area_rectangle(5, 3)
## [1] 15

Exporting Data and Plots

R can export data frames to CSV files and save plots as image files. The following code writes the employee data to a CSV file and saves the scatter plot as a PNG image.

# Export data to a CSV file
write.csv(employee_data, "employee_data.csv", row.names = FALSE)

# Save the plot as a PNG image
ggsave("scatter_plot.png",
       plot = scatter_plot,
       width = 10,
       height = 7,
       units = "cm")

Creating Tables

The summary() function provides descriptive statistics for the data frame. The kable() function from the knitr package presents those results in a formatted table in the knitted document.

summary(employee_data)
##        names        ages         salaries     
##  Length   :5   Min.   :22.0   Min.   :200000  
##  N.unique :5   1st Qu.:25.0   1st Qu.:210000  
##  N.blank  :0   Median :26.0   Median :250000  
##  Min.nchar:4   Mean   :26.4   Mean   :248000  
##  Max.nchar:6   3rd Qu.:29.0   3rd Qu.:280000  
##                Max.   :30.0   Max.   :300000
knitr::kable(as.data.frame(summary(employee_data)),
             caption = "Summary of Employee Data")
Summary of Employee Data
Var1 Var2 Freq
names Length :5
names N.unique :5
names N.blank :0
names Min.nchar:4
names Max.nchar:6
names NA
ages Min. :22.0
ages 1st Qu.:25.0
ages Median :26.0
ages Mean :26.4
ages 3rd Qu.:29.0
ages Max. :30.0
salaries Min. :200000
salaries 1st Qu.:210000
salaries Median :250000
salaries Mean :248000
salaries 3rd Qu.:280000
salaries Max. :300000

Using Pipes (%>% / |>) with dplyr

The native pipe |> passes the result of one operation to the next. In this example, dplyr filters the data to include employees earning more than 250,000 and then calculates the average age of those employees.

library(dplyr)

# Filter and summarise data using pipes
employee_data |>
  filter(salaries > 250000) |>
  summarize(ave_age = mean(ages))
##   ave_age
## 1    25.5