Challenge 9

challenge_9
Creating a function
Author

Calvin Cuff

Published

January 24, 2024

library(here)
library(readr)
library(readxl)
library(tidyverse)
library(ggplot2)

knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)

Challenge Overview

Today’s challenge is simple. Create a function, and use it to perform a data analysis / cleaning / visualization task:

Examples of such functions are: 1) A function that reads in and cleans a dataset. 2) A function that computes summary statistics (e.g., computes the z score for a variable).
3) A function that plots a histogram.

That’s it!

This is an intentionally straightforward challenge. You can use any dataset in the challenge datasets folder.

Function to read in a generic file

This function will read in a given dataset of a generic file extension. It supports extension types of csv, xlsx, and xls. It also accepts a second argument denoting how many rows to skip when reading the data.

read_data <- function(file_name, num_skip) {
  file_extension <- tools::file_ext(file_name)
  
  data <- switch(file_extension,
    csv = read_csv(file_name, skip=num_skip),
    xlsx = read_excel(file_name, skip=num_skip),
    xls = read_excel(file_name, skip=num_skip),
    "Unsupported file type"
  )
  
  return(data)
}

Running the function against 3 files of varying formats and one with an unsupported extension type. We can see the 3 different file types are read in to data frames and the unknown file gives an error message of unsupported file type.

railroad <- read_data("data/railroad_2012_clean_county.csv", 0)
head(railroad)
# A tibble: 6 × 3
  state county               total_employees
  <chr> <chr>                          <dbl>
1 AE    APO                                2
2 AK    ANCHORAGE                          7
3 AK    FAIRBANKS NORTH STAR               2
4 AK    JUNEAU                             3
5 AK    MATANUSKA-SUSITNA                  2
6 AK    SITKA                              1
state_county <- read_data("data/StateCounty2012.xls", 3)
head(state_county)
# A tibble: 6 × 5
  STATE     ...2  COUNTY               ...4  TOTAL
  <chr>     <lgl> <chr>                <lgl> <dbl>
1 AE        NA    APO                  NA        2
2 AE Total1 NA    <NA>                 NA        2
3 AK        NA    ANCHORAGE            NA        7
4 AK        NA    FAIRBANKS NORTH STAR NA        2
5 AK        NA    JUNEAU               NA        3
6 AK        NA    MATANUSKA-SUSITNA    NA        2
debt <- read_data("data/debt_in_trillions.xlsx", 0)
head(debt)
# A tibble: 6 × 8
  `Year and Quarter` Mortgage `HE Revolving` `Auto Loan` `Credit Card`
  <chr>                 <dbl>          <dbl>       <dbl>         <dbl>
1 03:Q1                  4.94          0.242       0.641         0.688
2 03:Q2                  5.08          0.26        0.622         0.693
3 03:Q3                  5.18          0.269       0.684         0.693
4 03:Q4                  5.66          0.302       0.704         0.698
5 04:Q1                  5.84          0.328       0.72          0.695
6 04:Q2                  5.97          0.367       0.743         0.697
# ℹ 3 more variables: `Student Loan` <dbl>, Other <dbl>, Total <dbl>
unknown <- read_data("data/unknown.txt", 0)
head(unknown)
[1] "Unsupported file type"

Function to compute z-score

This function will compute the z-score for a particular value. It accepts one parameter x, which is the value being evaluated, and col, the rest of the data to be evaluated against.

z_score <- function(x, col) {
  z <- (x - mean(col))/sd(col)
  return(z)
}

# Select arbitray value
my_mortgage_val <- debt[1, 2]

# Calculate z-score for specific mortgage value
z_score(my_mortgage_val, debt$Mortgage)
   Mortgage
1 -2.812098