Data Exploration

Exercises ~ Week 2

logo


1 Exercise 1

The following table shows sample information for three students. Each observation represents a single student and includes details such as their unique student ID, name, age, total credits completed, major field of study, and year level.

This dataset demonstrates a mixture of variable types:

  • Nominal: StudentID, Name, Major
  • Numeric: Age (continuous), CreditsCompleted (discrete)
  • Ordinal: YearLevel (Freshman → Senior)
StudentID Name Age CreditsCompleted Major YearLevel
S001 Alice 20 45 Data Sains Sophomore
S002 Budi 21 60 Mathematics Junior
S003 Citra 19 30 Statistics Freshman
# 1. Create vectors for each variable
StudentID <- c("S001", "S002", "S003")       # Nominal / ID
Name <- c("Alice", "Budi", "Citra")          # Nominal / Name
Age <- c(20, 21, 19)                         # Numeric / Continuous
CreditsCompleted <- c(45, 60, 30)            # Numeric / Discrete

# Nominal
Major <- c("Data Sains", "Mathematics", "Statistics")  

# Ordinal
YearLevel <- factor(c("Sophomore", "Junior", "Freshman"),
                    levels = c("Freshman","Sophomore","Junior","Senior"),
                    ordered = TRUE)          

# 2. Combine all vectors into a data frame
students <- data.frame(
  StudentID, Name, Age, CreditsCompleted, Major, YearLevel,
  stringsAsFactors = FALSE
)

# 3. Display the data frame
print(students)
##   StudentID  Name Age CreditsCompleted       Major YearLevel
## 1      S001 Alice  20               45  Data Sains Sophomore
## 2      S002  Budi  21               60 Mathematics    Junior
## 3      S003 Citra  19               30  Statistics  Freshman

2 Exercise 2

Identify Data Types: Determine the type of data for each of the following variables:

# Install knitr package if not already installed
# install.packages("knitr")
library(knitr)

# Create a data frame for Data Types
variables_info <- data.frame(
  No = 1:5,
  Variable = c(
    "Number of vehicles passing through the toll road each day",
    "Student height in cm",
    "Employee gender (Male / Female)",
    "Customer satisfaction level: Low, Medium, High",
    "Respondent's favorite color: Red, Blue, Green"
  ),
  DataType = c(
    "numeric",
    "numeric",
    "kategorikal",
    "kategorikal",
    "kategorikal"
  ),
  Subtype = c(
    "diskrit",
    "kontinu",
    "nominal",
    "ordinal",
    "nominal"
  ),
  stringsAsFactors = FALSE
)

# Display the data frame as a neat table
kable(variables_info, 
      caption = "Table of Variables and Data Types")
Table of Variables and Data Types
No Variable DataType Subtype
1 Number of vehicles passing through the toll road each day numeric diskrit
2 Student height in cm numeric kontinu
3 Employee gender (Male / Female) kategorikal nominal
4 Customer satisfaction level: Low, Medium, High kategorikal ordinal
5 Respondent’s favorite color: Red, Blue, Green kategorikal nominal

3 Exercise 3

Classify Data Sources: Determine whether the following data comes from internal or external sources, and whether it is structured or unstructured:

# Install DT package if not already installed
# install.packages("DT")
library(DT)

# Create a data frame for data sources 
data_sources <- data.frame(
  No = 1:4,
  DataSource = c(
    "Daily sales transaction data of the company",
    "Weather reports from BMKG",
    "Product reviews on social media",
    "Warehouse inventory reports"
  ),
  Internal_External = c(
    "internal",
    "eksternal",
    "eksternal",
    "internal"
  ),
  Structured_Unstructured = c(
    "structured",
    "structured",
    "unstructured",
    "structured"
  ),
  stringsAsFactors = FALSE
)

# Display the data frame as a neat table
datatable(data_sources, 
          caption = "Table of Data Sources",
          rownames = FALSE) # hides the index column

4 Exercise 4

Dataset Structure: Consider the following transaction table:

Date Qty Price Product CustomerTier Total
2025-10-01 2 1000 Laptop High 2000
2025-10-01 5 20 Mouse Medium 100
2025-10-02 1 1000 Laptop Low 1000
2025-10-02 3 30 Keyboard Medium 90
2025-10-03 4 50 Mouse Medium 200
2025-10-03 2 1000 Laptop High 2000
2025-10-04 6 25 Keyboard Low 150
2025-10-04 1 1000 Laptop High 1000
2025-10-05 3 40 Mouse Low 120
2025-10-05 5 10 Keyboard Medium 50

Your Assignment Instructions: Creating a Transactions Table above in R

  1. Create a data frame in R called transactions containing the data above.

  2. Identify which variables are numeric and which are categorical

Identification

NO Variable Qualified of Data Type
1. Date categorical(ordinal)
2. Qty Numerik(discrete)
3. Price Numerik
4. Product Categorical(nominal)
5. Customer Tier Categorical(nominal)
6. Total Numerik(disctere)
  1. Calculate total revenue for each transaction by multiplying Qty × Price and add it as a new column Total.

  2. Compute summary statistics - Total quantity sold for each product

    • total revenua per product -average price per product
  3. Visualize the data:

    • Create a barplot showing total quantity sold per product.
    • Create a pie chart showing the proportion of total revenue per customer tier.
  4. Optional Challenge:

    • Find which date had the highest total revenue.
    • Create a stacked bar chart showing quantity sold per product by customer tier.

Hints: Use data.frame(), aggregate(), barplot(), pie(), and basic arithmetic operations in R.

transactions <- data.frame(
  Date = as.Date(c(
    "2025-10-01", "2025-10-01", "2025-10-02", "2025-10-02",
    "2025-10-03", "2025-10-03", "2025-10-04", "2025-10-04",
    "2025-10-05", "2025-10-05"
  )),
  Qty = c(2, 5, 1, 3, 4, 2, 6, 1, 3, 5),
  Price = c(1000, 20, 1000, 30, 50, 1000, 25, 1000, 40, 10),
  Product = c("Laptop", "Mouse", "Laptop", "Keyboard", "Mouse",
              "Laptop", "Keyboard", "Laptop", "Mouse", "Keyboard"),
  CustomerTier = c("High", "Medium", "Low", "Medium", "Medium",
                   "High", "Low", "High", "Low", "Medium"),
  stringsAsFactors = FALSE
)

transactions
str(transactions)
## 'data.frame':    10 obs. of  5 variables:
##  $ Date        : Date, format: "2025-10-01" "2025-10-01" ...
##  $ Qty         : num  2 5 1 3 4 2 6 1 3 5
##  $ Price       : num  1000 20 1000 30 50 1000 25 1000 40 10
##  $ Product     : chr  "Laptop" "Mouse" "Laptop" "Keyboard" ...
##  $ CustomerTier: chr  "High" "Medium" "Low" "Medium" ...
transactions$Total <- transactions$Qty * transactions$Price
transactions
# Total quantity sold per product
total_qty <- aggregate(Qty ~ Product, data = transactions, sum)

# Total revenue per product
total_revenue <- aggregate(Total ~ Product, data = transactions, sum)

# Average price per product
avg_price <- aggregate(Price ~ Product, data = transactions, mean)

total_qty
total_revenue
avg_price
# Barplot total quantity sold per product
barplot(
  total_qty$Qty,
  names.arg = total_qty$Product,
  col = "purple",
  main = "Total Quantity Sold per Product",
  xlab = "Product",
  ylab = "Total Quantity"
)

# Pie chart total revenue per customer tier
# Pie Chart: Total Revenue per Customer Tier

# 1. Summarize total revenue by customer tier
revenue_tier <- aggregate(Total ~ CustomerTier, data = transactions, sum)

# 2. Coral color palette
coral_palette <- c("#FF7F50", "#FF6F61", "#FFA07A")  
# Coral, Deep Coral, Light Coral

# 3. Calculate percentage for each tier
percentages <- round(100 * revenue_tier$Total / sum(revenue_tier$Total), 1)

# 4. Combine labels: tier name + percentage + total value
labels <- paste0(
  revenue_tier$CustomerTier, 
  "\n", percentages, "% (", revenue_tier$Total, ")"
)

# 5. Create pie chart
pie(
  revenue_tier$Total,
  labels = labels,
  main = "Proportion of Total Revenue per Customer Tier",
  col = coral_palette,
  clockwise = TRUE,
  border = "white"
)

# 6. Add legend on the right side
legend(
  "topright",
  legend = paste(revenue_tier$CustomerTier, "-", percentages, "%"),
  fill = coral_palette,
  border = "white",
  title = "Customer Tier",
  bty = "n"
)

# Find the date with the highest total revenue
revenue_date <- aggregate(Total ~ Date, data = transactions, sum)
revenue_date[which.max(revenue_date$Total), ]
# Stacked bar chart: quantity sold per product by customer tier
# Stacked Bar Chart: Quantity Sold per Product by Customer Tier

library(reshape2)

# Make summary of total quantity by product and customer tier
qty_tier <- aggregate(Qty ~ Product + CustomerTier, data = transactions, sum)

# Change to wide format (rows = Product, columns = Customer Tier)
qty_wide <- dcast(qty_tier, Product ~ CustomerTier, value.var = "Qty", fill = 0)

# Coral colors
coral_colors <- c("#FF7F50", "#FF6F61", "#FFA07A")

# Change to matrix for barplot
qty_matrix <- as.matrix(qty_wide[, -1])

# Calculate total per product
total_per_product <- rowSums(qty_matrix)

# Calculate percent for each part
percent <- round(qty_matrix / total_per_product * 100, 1)

# Make the stacked bar chart
bar_pos <- barplot(
  t(qty_matrix),
  col = coral_colors,
  beside = FALSE,
  legend = colnames(qty_wide)[-1],
  main = "Quantity Sold per Product by Customer Tier",
  xlab = "Product",
  ylab = "Quantity",
  names.arg = qty_wide$Product,
  border = "white"
)

# Add labels: number + percent
for (i in 1:nrow(qty_matrix)) {
  y_bottom <- 0
  for (j in 1:ncol(qty_matrix)) {
    value <- qty_matrix[i, j]
    label <- paste0(value, " (", percent[i, j], "%)")
    text(bar_pos[i], y_bottom + value / 2, labels = label, cex = 0.8)
    y_bottom <- y_bottom + value
  }
}

## Exercise 5

Create Your Own Data Frame:

Objective: Create a data frame in R with 30 rows containing a mix of data types: continuous, discrete, nominal, and ordinal.

4.1 Instructions

  1. Open RStudio or the R console.

  2. Create a vector for each column in your data frame:

    • Date: 30 dates (can be sequential or random within a month/year)
    • Continuous: numeric values that can take decimal values (e.g., height, weight, temperature)
    • Discrete: numeric values that can only take whole numbers (e.g., number of items, number of vehicles)
    • Nominal: categorical values with no order (e.g., color, gender, city)
    • Ordinal: categorical values with a defined order (e.g., Low, Medium, High; Beginner, Intermediate, Expert)
  3. Combine all vectors into a data frame called my_data.

  4. Check your data frame using head() or View() to ensure it has 30 rows and the columns are correct.

  5. Optional tasks:

    • Summarize each column using summary()
    • Count the frequency of each category for Nominal and Ordinal columns using table()

4.2 Hints

  • Use seq.Date() or as.Date() to generate the Date column.
  • Use runif() or rnorm() for continuous numeric data.
  • Use sample() for discrete, nominal, and ordinal data.
  • Ensure the ordinal vector is created with factor(..., levels = c("Low","Medium","High"), ordered = TRUE) (or similar).
# ============================
# CHUNK 1: Buat Data Frame
# ============================

# Set seed agar hasil acak selalu sama
set.seed(123)

# Buat 30 data
n <- 30

# Continuous (misal: tinggi badan dalam cm)
continuous <- rnorm(n, mean = 170, sd = 10)

# Discrete (misal: jumlah saudara)
discrete <- sample(0:5, n, replace = TRUE)

# Nominal (misal: jenis kelamin)
nominal <- sample(c("Male", "Female"), n, replace = TRUE)

# Ordinal (misal: tingkat pendidikan)
ordinal <- factor(
  sample(c("SD", "SMP", "SMA", "S1", "S2"), n, replace = TRUE),
  levels = c("SD", "SMP", "SMA", "S1", "S2"),
  ordered = TRUE
)

# Gabungkan semua ke dalam data frame
df <- data.frame(
  continuous = continuous,
  discrete = discrete,
  categorical_nominal = nominal,
  categorical_ordinal = ordinal
)

# Tampilkan data frame
print(df)
##    continuous discrete categorical_nominal categorical_ordinal
## 1    164.3952        4              Female                 SMA
## 2    167.6982        3              Female                 SMP
## 3    185.5871        4                Male                 SMP
## 4    170.7051        1              Female                 SMP
## 5    171.2929        0              Female                  S1
## 6    187.1506        0                Male                 SMP
## 7    174.6092        2                Male                 SMP
## 8    157.3494        0                Male                  S1
## 9    163.1315        5              Female                  S1
## 10   165.5434        4              Female                  SD
## 11   182.2408        0              Female                 SMA
## 12   173.5981        1              Female                 SMA
## 13   174.0077        3                Male                  SD
## 14   171.1068        3                Male                 SMA
## 15   164.4416        5              Female                  S2
## 16   187.8691        5              Female                 SMP
## 17   174.9785        2              Female                 SMA
## 18   150.3338        5                Male                 SMP
## 19   177.0136        5              Female                  S2
## 20   165.2721        0                Male                  S2
## 21   159.3218        5              Female                 SMA
## 22   167.8203        1                Male                  S1
## 23   159.7400        0                Male                  S1
## 24   162.7111        1                Male                  S1
## 25   163.7496        3              Female                  S2
## 26   153.1331        4              Female                 SMA
## 27   178.3779        4                Male                  SD
## 28   171.5337        5                Male                 SMP
## 29   158.6186        2                Male                  SD
## 30   182.5381        0              Female                 SMP