Lab 1: Data Manipulation and Visualizations

Welcome to Lab 1! In this session, we’ll be using R to manipulate data and create a variety of visualizations. By the end of this lab, you’ll have a solid foundation in using R for basic data analysis and visualization.

Objectives

  1. Setup:
    • Download and install R and RStudio.
    • Set up your workspace by creating a “Data Viz” folder on your drive (U-Drive, Google Drive, etc.).
  2. Loading Data:
    • Load a dataset into R using the read.csv() function.
    • Explore the data using summary() and str() functions.
  3. Creating Visualizations:
    • Generate various types of visualizations to explore categorical data:
      • Bar charts
      • Pie charts
      • Boxplots
  4. Saving Your Work:
    • Save your R script and export your visualizations.

Step 1: Setup Your Workspace

  1. Download R and RStudio:
    • Download the latest version of R from r-project.org.
    • Download RStudio from rstudio.com.
    • Install both programs following the prompts.
  2. Create a Working Directory:

Step 2: Loading and Exploring Data For this lab, we’ll use the Titanic dataset. Download it from Kaggle and save it to your working directory. Load the dataset into R:

library(readr)
titanic_data <- read_csv("titanicdata.csv")
## Rows: 891 Columns: 12
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): Name, Sex, Ticket, Cabin, Embarked
## dbl (7): PassengerId, Survived, Pclass, Age, SibSp, Parch, Fare
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Explore the Dataset:

Get a summary of the data:
summary(titanic_data)
##   PassengerId       Survived          Pclass          Name          
##  Min.   :  1.0   Min.   :0.0000   Min.   :1.000   Length:891        
##  1st Qu.:223.5   1st Qu.:0.0000   1st Qu.:2.000   Class :character  
##  Median :446.0   Median :0.0000   Median :3.000   Mode  :character  
##  Mean   :446.0   Mean   :0.3838   Mean   :2.309                     
##  3rd Qu.:668.5   3rd Qu.:1.0000   3rd Qu.:3.000                     
##  Max.   :891.0   Max.   :1.0000   Max.   :3.000                     
##                                                                     
##      Sex                 Age            SibSp           Parch       
##  Length:891         Min.   : 0.42   Min.   :0.000   Min.   :0.0000  
##  Class :character   1st Qu.:20.12   1st Qu.:0.000   1st Qu.:0.0000  
##  Mode  :character   Median :28.00   Median :0.000   Median :0.0000  
##                     Mean   :29.70   Mean   :0.523   Mean   :0.3816  
##                     3rd Qu.:38.00   3rd Qu.:1.000   3rd Qu.:0.0000  
##                     Max.   :80.00   Max.   :8.000   Max.   :6.0000  
##                     NA's   :177                                     
##     Ticket               Fare           Cabin             Embarked        
##  Length:891         Min.   :  0.00   Length:891         Length:891        
##  Class :character   1st Qu.:  7.91   Class :character   Class :character  
##  Mode  :character   Median : 14.45   Mode  :character   Mode  :character  
##                     Mean   : 32.20                                        
##                     3rd Qu.: 31.00                                        
##                     Max.   :512.33                                        
## 
##    Check the structure of the dataset:
 str(titanic_data)
## spc_tbl_ [891 × 12] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ PassengerId: num [1:891] 1 2 3 4 5 6 7 8 9 10 ...
##  $ Survived   : num [1:891] 0 1 1 1 0 0 0 0 1 1 ...
##  $ Pclass     : num [1:891] 3 1 3 1 3 3 1 3 3 2 ...
##  $ Name       : chr [1:891] "Braund, Mr. Owen Harris" "Cumings, Mrs. John Bradley (Florence Briggs Thayer)" "Heikkinen, Miss. Laina" "Futrelle, Mrs. Jacques Heath (Lily May Peel)" ...
##  $ Sex        : chr [1:891] "male" "female" "female" "female" ...
##  $ Age        : num [1:891] 22 38 26 35 35 NA 54 2 27 14 ...
##  $ SibSp      : num [1:891] 1 1 0 1 0 0 0 3 0 1 ...
##  $ Parch      : num [1:891] 0 0 0 0 0 0 0 1 2 0 ...
##  $ Ticket     : chr [1:891] "A/5 21171" "PC 17599" "STON/O2. 3101282" "113803" ...
##  $ Fare       : num [1:891] 7.25 71.28 7.92 53.1 8.05 ...
##  $ Cabin      : chr [1:891] NA "C85" NA "C123" ...
##  $ Embarked   : chr [1:891] "S" "C" "S" "S" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   PassengerId = col_double(),
##   ..   Survived = col_double(),
##   ..   Pclass = col_double(),
##   ..   Name = col_character(),
##   ..   Sex = col_character(),
##   ..   Age = col_double(),
##   ..   SibSp = col_double(),
##   ..   Parch = col_double(),
##   ..   Ticket = col_character(),
##   ..   Fare = col_double(),
##   ..   Cabin = col_character(),
##   ..   Embarked = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>

Step 3: Creating Visualizations

Bar Chart: Create a bar chart to visualize the number of passengers by class:

barplot(table(titanic_data$Pclass),
        main="Number of Passengers by Class",
        xlab="Passenger Class",
        ylab="Number of Passengers",
        col="lightblue")

## Majority of the passengers were in the third class.

Pie Chart:

Visualize the proportion of passengers who survived:
pie(table(titanic_data$Survived),
    labels=c("Did Not Survive", "Survived"),
    main="Survival Proportion",
    col=c("red", "green"))

## Over 50% of passengers did not survive. 

Boxplot:

Create a boxplot to visualize the distribution of ages across different passenger classes:
    boxplot(titanic_data$Age ~ titanic_data$Pclass,
            main="Age Distribution by Passenger Class",
            xlab="Passenger Class",
            ylab="Age",
            col="orange")

## Class 1 has the most variability in ages. 

Step 4: Saving and Exporting Work

Save Your R Script: Save your script by clicking on the save icon or using Ctrl + S in RStudio.

Export Visualizations:

    To save your visualizations, use the export button in the "Plots" pane:
        Click on “Export” > “Save as Image” or “Save as PDF”.
        Choose your preferred file format and location.

# Submit Your Lab Report: Compile all visualizations into a Word document. Include the R code used for each visualization and a brief explanation. Submit your document via Moodle by the deadline.

Examples and Explanations

Bar Chart Example:

The bar chart generated in this lab shows the distribution of passengers by class. This type of visualization is useful for understanding categorical data distribution at a glance.

Pie Chart Example:

The pie chart displays the survival rates of Titanic passengers, providing a visual representation of the proportion of survivors vs. non-survivors.

Boxplot Example:

The boxplot illustrates the variation in age across different passenger classes, which helps in identifying any patterns or outliers in the data.

Instructions to Use the R Markdown File:

  1. Save the R Markdown code into an .Rmd file, for example, DataViz_Lab1.Rmd.
  2. Open the file** in RStudio.
  3. Click on the “Knit” button in the RStudio toolbar and select “Knit to PDF”.
  4. RStudio will generate a PDF document that includes the lab activity content, code, and visualizations.

This setup allows you to easily generate a polished PDF report directly from RStudio with all the lab instructions, examples, and graphics embedded.

Your Homework:

Go to

  1. Find a data set that interest you.
  2. download the CSV file and upload it to R
  3. Explore this data set and create visualizations of at least one categorical variable.
  4. Submit a PDF file showing the knitted file with the examples and the visualizations of the variable you chose. Include a paragraph the summarizes the description of this data set and the insights you gain from the viz you created.
library(readr)
coffe_data <- read_csv("Coffe_sales.csv")
## Rows: 3547 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): cash_type, coffee_name, Time_of_Day, Weekday, Month_name
## dbl  (4): hour_of_day, money, Weekdaysort, Monthsort
## date (1): Date
## time (1): Time
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
summary(coffe_data)
##   hour_of_day     cash_type             money       coffee_name       
##  Min.   : 6.00   Length:3547        Min.   :18.12   Length:3547       
##  1st Qu.:10.00   Class :character   1st Qu.:27.92   Class :character  
##  Median :14.00   Mode  :character   Median :32.82   Mode  :character  
##  Mean   :14.19                      Mean   :31.65                     
##  3rd Qu.:18.00                      3rd Qu.:35.76                     
##  Max.   :22.00                      Max.   :38.70                     
##  Time_of_Day          Weekday           Month_name         Weekdaysort   
##  Length:3547        Length:3547        Length:3547        Min.   :1.000  
##  Class :character   Class :character   Class :character   1st Qu.:2.000  
##  Mode  :character   Mode  :character   Mode  :character   Median :4.000  
##                                                           Mean   :3.846  
##                                                           3rd Qu.:6.000  
##                                                           Max.   :7.000  
##    Monthsort           Date                 Time                
##  Min.   : 1.000   Min.   :2024-03-01   Min.   :06:50:04.000000  
##  1st Qu.: 3.000   1st Qu.:2024-07-17   1st Qu.:10:57:06.000000  
##  Median : 7.000   Median :2024-10-10   Median :14:31:28.000000  
##  Mean   : 6.454   Mean   :2024-10-04   Mean   :14:40:35.531717  
##  3rd Qu.:10.000   3rd Qu.:2025-01-11   3rd Qu.:18:11:31.000000  
##  Max.   :12.000   Max.   :2025-03-23   Max.   :22:59:18.000000
str(coffe_data)
## spc_tbl_ [3,547 × 11] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ hour_of_day: num [1:3547] 10 12 12 13 13 15 16 18 19 19 ...
##  $ cash_type  : chr [1:3547] "card" "card" "card" "card" ...
##  $ money      : num [1:3547] 38.7 38.7 38.7 28.9 38.7 33.8 38.7 33.8 38.7 33.8 ...
##  $ coffee_name: chr [1:3547] "Latte" "Hot Chocolate" "Hot Chocolate" "Americano" ...
##  $ Time_of_Day: chr [1:3547] "Morning" "Afternoon" "Afternoon" "Afternoon" ...
##  $ Weekday    : chr [1:3547] "Fri" "Fri" "Fri" "Fri" ...
##  $ Month_name : chr [1:3547] "Mar" "Mar" "Mar" "Mar" ...
##  $ Weekdaysort: num [1:3547] 5 5 5 5 5 5 5 5 5 5 ...
##  $ Monthsort  : num [1:3547] 3 3 3 3 3 3 3 3 3 3 ...
##  $ Date       : Date[1:3547], format: "2024-03-01" "2024-03-01" ...
##  $ Time       : 'hms' num [1:3547] 10:15:50 12:19:22 12:20:18 13:46:33 ...
##   ..- attr(*, "units")= chr "secs"
##  - attr(*, "spec")=
##   .. cols(
##   ..   hour_of_day = col_double(),
##   ..   cash_type = col_character(),
##   ..   money = col_double(),
##   ..   coffee_name = col_character(),
##   ..   Time_of_Day = col_character(),
##   ..   Weekday = col_character(),
##   ..   Month_name = col_character(),
##   ..   Weekdaysort = col_double(),
##   ..   Monthsort = col_double(),
##   ..   Date = col_date(format = ""),
##   ..   Time = col_time(format = "")
##   .. )
##  - attr(*, "problems")=<externalptr>
barplot(table(coffe_data$Weekday),
        main="Number of Coffee Sales by Weekday",
        xlab="Weekday",
        ylab="Number of Sales",
        col="lightpink")

This data set displays coffee shop transaction records. It has details about sales, payment type, time of purchase, and customer preferences. My graph displays the number of coffee sales from this particular shop each day of the week. From my graph, we are able to clearly see that this coffee shop is in a time period of pretty steady sales throughout the week. We see a decline in sales on Sunday which could be due to many possibilities. This could be due to limited store hours, fewer commuters and workers, and different customer routines (some may sleep in or stay home).