Constructing an R Package: Technical and Community Viewpoints

In this project, I will describe the package at two distinct levels: a technical perspective and a perspective tailored to the R community. First, the technical perspective will focus on the package’s internal architecture; second, the R community perspective will emphasize usability, documentation, and integration with existing R workflows.

Load Packages

library(devtools)
## Loading required package: usethis
library(usethis)
library(roxygen2)
library(testthat)
## 
## Attaching package: 'testthat'
## The following object is masked from 'package:devtools':
## 
##     test_file
library(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ lubridate 1.9.5     ✔ tibble    3.3.1
## ✔ purrr     1.2.2     ✔ tidyr     1.3.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ readr::edition_get()   masks testthat::edition_get()
## ✖ dplyr::filter()        masks stats::filter()
## ✖ dplyr::lag()           masks stats::lag()
## ✖ readr::local_edition() masks testthat::local_edition()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(dplyr)

Source:https://usafacts.org/articles/what-is-ice-and-what-does-it-do/

ICE DETENTION

Undocumented immigrants in the United States encounter significant challenges, facing numerous obstacles today. As an immigrant myself, I find it hard to ignore data on arrests, detentions, and deportations, whether reported monthly or annually. Thus, I recognized the need to ascertain the annual number of immigrants detained overall between 2014 and 2025, and to identify the country with the highest detention rate. This goal directed my choice of the detention dataset for my final project. The project will deliver visual analysis and implement the recommendations in an installable R package that includes comprehensive documentation and necessary structures. Furthermore, this project benefits both me and others, informs policy debates, provides actionable insights to stakeholders, supports future research, enhances public understanding, guides decision-makers, and promotes informed discussion.

Read and Investigate the Data

# Load ice detention dataset
detention <- read_csv("data-raw/ice_detention.csv")
## Rows: 12 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (13): Fiscal Year, Total, Colombia, India, Venezuela, Nicaragua, Guatema...
## 
## ℹ 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.
head(detention)
## # A tibble: 6 × 13
##   `Fiscal Year`  Total Colombia India Venezuela Nicaragua Guatemala Honduras
##           <dbl>  <dbl>    <dbl> <dbl>     <dbl>     <dbl>     <dbl>    <dbl>
## 1          2014 425730     1560  2310       270      2380     74540    76710
## 2          2015 307340     1500  2970       270      1470     52560    34900
## 3          2016 352880     1540  4090       460      1540     65760    46750
## 4          2017 323590     1450  3660       670      1510     62740    43410
## 5          2018 396450     1580  9820      1130      3430     99750    62460
## 6          2019 510850     1660  8450      3250      7890    152250   104170
## # ℹ 5 more variables: Mexico <dbl>, `Dominican Republic` <dbl>, Other <dbl>,
## #   `El Salvador` <dbl>, Ecuador <dbl>

Inspect before renaming

dim(detention)
## [1] 12 13

The detention dataset consists of 12 observations(rows) and 13 variables(columns).

names(detention)
##  [1] "Fiscal Year"        "Total"              "Colombia"          
##  [4] "India"              "Venezuela"          "Nicaragua"         
##  [7] "Guatemala"          "Honduras"           "Mexico"            
## [10] "Dominican Republic" "Other"              "El Salvador"       
## [13] "Ecuador"
glimpse(detention)
## Rows: 12
## Columns: 13
## $ `Fiscal Year`        <dbl> 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2…
## $ Total                <dbl> 425730, 307340, 352880, 323590, 396450, 510850, 1…
## $ Colombia             <dbl> 1560, 1500, 1540, 1450, 1580, 1660, 1160, 3120, 3…
## $ India                <dbl> 2310, 2970, 4090, 3660, 9820, 8450, 1280, 1840, 9…
## $ Venezuela            <dbl> 270, 270, 460, 670, 1130, 3250, 1250, 23480, 3669…
## $ Nicaragua            <dbl> 2380, 1470, 1540, 1510, 3430, 7890, 1470, 26920, …
## $ Guatemala            <dbl> 74540, 52560, 65760, 62740, 99750, 152250, 30720,…
## $ Honduras             <dbl> 76710, 34900, 46750, 43410, 62460, 104170, 16860,…
## $ Mexico               <dbl> 172560, 143830, 134550, 121410, 139970, 121260, 8…
## $ `Dominican Republic` <dbl> 3380, 2760, 2790, 2600, 2400, 2650, 1980, 2080, 4…
## $ Other                <dbl> 26740, 23730, 34250, 41230, 40200, 59160, 26450, …
## $ `El Salvador`        <dbl> 59930, 40260, 57950, 42460, 33170, 43410, 11110, …
## $ Ecuador              <dbl> 5350, 3100, 3200, 2460, 2550, 6710, 3910, 17400, …
# View structure
str(detention)
## spc_tbl_ [12 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Fiscal Year       : num [1:12] 2014 2015 2016 2017 2018 ...
##  $ Total             : num [1:12] 425730 307340 352880 323590 396450 ...
##  $ Colombia          : num [1:12] 1560 1500 1540 1450 1580 ...
##  $ India             : num [1:12] 2310 2970 4090 3660 9820 8450 1280 1840 9210 7530 ...
##  $ Venezuela         : num [1:12] 270 270 460 670 1130 ...
##  $ Nicaragua         : num [1:12] 2380 1470 1540 1510 3430 ...
##  $ Guatemala         : num [1:12] 74540 52560 65760 62740 99750 ...
##  $ Honduras          : num [1:12] 76710 34900 46750 43410 62460 ...
##  $ Mexico            : num [1:12] 172560 143830 134550 121410 139970 ...
##  $ Dominican Republic: num [1:12] 3380 2760 2790 2600 2400 ...
##  $ Other             : num [1:12] 26740 23730 34250 41230 40200 ...
##  $ El Salvador       : num [1:12] 59930 40260 57950 42460 33170 ...
##  $ Ecuador           : num [1:12] 5350 3100 3200 2460 2550 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   `Fiscal Year` = col_double(),
##   ..   Total = col_double(),
##   ..   Colombia = col_double(),
##   ..   India = col_double(),
##   ..   Venezuela = col_double(),
##   ..   Nicaragua = col_double(),
##   ..   Guatemala = col_double(),
##   ..   Honduras = col_double(),
##   ..   Mexico = col_double(),
##   ..   `Dominican Republic` = col_double(),
##   ..   Other = col_double(),
##   ..   `El Salvador` = col_double(),
##   ..   Ecuador = col_double()
##   .. )
##  - attr(*, "problems")=<pointer: 0x000001d8109ff7a0>
# Summarise(detention)
summary(detention)
##   Fiscal Year       Total           Colombia         India     
##  Min.   :2014   Min.   : 44750   Min.   : 1160   Min.   :1280  
##  1st Qu.:2017   1st Qu.:257778   1st Qu.: 1530   1st Qu.:2195  
##  Median :2020   Median :309460   Median : 1620   Median :3875  
##  Mean   :2020   Mean   :301552   Mean   : 9196   Mean   :4951  
##  3rd Qu.:2022   3rd Qu.:363773   3rd Qu.: 7490   3rd Qu.:7760  
##  Max.   :2025   Max.   :510850   Max.   :39270   Max.   :9820  
##    Venezuela         Nicaragua       Guatemala         Honduras     
##  Min.   :  270.0   Min.   :  610   Min.   :  4670   Min.   :  4510  
##  1st Qu.:  617.5   1st Qu.: 1500   1st Qu.: 15935   1st Qu.: 15922  
##  Median : 1215.0   Median : 2905   Median : 44330   Median : 31440  
##  Mean   : 8516.7   Mean   : 9174   Mean   : 51438   Mean   : 38648  
##  3rd Qu.:15982.5   3rd Qu.: 8502   3rd Qu.: 67955   3rd Qu.: 50678  
##  Max.   :36690.0   Max.   :48070   Max.   :152250   Max.   :104170  
##      Mexico       Dominican Republic     Other         El Salvador   
##  Min.   : 12240   Min.   :  940      Min.   : 11220   Min.   : 2240  
##  1st Qu.: 49683   1st Qu.: 2320      1st Qu.: 26668   1st Qu.: 8038  
##  Median :103975   Median : 2705      Median : 40715   Median :22140  
##  Mean   : 93670   Mean   : 3918      Mean   : 46902   Mean   :26733  
##  3rd Qu.:135905   3rd Qu.: 3760      3rd Qu.: 63115   3rd Qu.:42698  
##  Max.   :172560   Max.   :13130      Max.   :100720   Max.   :59930  
##     Ecuador     
##  Min.   : 2010  
##  1st Qu.: 2962  
##  Median : 4630  
##  Mean   : 8410  
##  3rd Qu.:13050  
##  Max.   :22940

Reshape the data

library(tidyr)

detention_long <- pivot_longer(
  detention,
  cols = Colombia:Ecuador,
  names_to = "Country",
  values_to = "Country Count"
)

Linear Regression of ICE Detentions by Fiscal Year

ggplot(detention,
       aes(x = `Fiscal Year`,
           y = Total)) +
  geom_point(
      alpha = 0.8,
      color = "cyan",
      size = 3
      ) +
 geom_smooth(
   method = "lm",
   color = "red"
   ) +
  
  labs(
    title = "ICE Detentions by Fiscal Year",
    x = "Fiscal Year",
    y = "Total Detentions"
  ) +
  theme_minimal()+
  theme(
    plot.title = element_text(hjust = 0.5, color = "blue")
  )

Analytical Approaches

The linear regression analysis indicates that the detention rate reached their highest level in 2019, suggesting a higher frequency of arrests during that year. This spike may be attributed to intensified law enforcement initiatives, changes in policy, or an increase in reported incidents. Over the subsequent years, the model shows a gradual decline in detention rates, reaching a lower level by 2025. The downward trend could reflect the effectiveness of reforms, improved community policing, or shifts in crime patterns.

# Create a vector country names
country_names <- c(
  "Colombia", "India", "Venezuela",
  "Nicaragua", "Guatemala", "Honduras",
  "Mexico", "Dominican Republic",
  "Other", "El Salvador", "Ecuador"
)

# Find Country Totals
country_totals <- colSums(detention[, 3:13], na.rm = TRUE)

Convert to a data frame for plotting

# create a dataframe for country_detentions
country_detentions <- data.frame(
  Country = country_names,
  Total = as.numeric(country_totals)
  )

Visualize total detention counts by country

ggplot(country_detentions, 
       aes(x = Country, 
           y = Total,
           colour = Country)) +
  geom_point(size = 4)+
  
  theme_minimal()+
  theme(
    plot.title = element_text(hjust = 0.5, color = "brown1"),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(), 
    axis.line = element_line(linewidth = 0.75),
    axis.line.x.bottom = element_line(colour = "blue2"),
   )+
      labs(
        title = "Total Detentions by Country",
        x = "Country",
        y = "Total Detentions"
      ) 

Concise Findings Statement

The geom_point plot shows that Mexico, represented by the blue point, has the highest total number of detentions among the countries displayed. This pattern can be plausibly explained by Mexico’s proximity to the United States, which allows a larger volume of cross‑border movement and thus raises the likelihood of detentions. Ecuador, often referred to in the data as the “brown point”, shows a markedly lower number of citizens detained by U.S. Immigration and Customs Enforcement (ICE).

Technical Communication 1

The ICE detention dataset holds yearly detention figures, arranged by fiscal year and the detainee’s country of birth. This arrangement lets analysis look at temporal trends and compare how people from various regions are treated. Prior to any statistical work, the dataset was examined with the head() function to see the initial entries and with str() to verify data types and variable labels.

Test Generic Functions

print(detention)
## # A tibble: 12 × 13
##    `Fiscal Year`  Total Colombia India Venezuela Nicaragua Guatemala Honduras
##            <dbl>  <dbl>    <dbl> <dbl>     <dbl>     <dbl>     <dbl>    <dbl>
##  1          2014 425730     1560  2310       270      2380     74540    76710
##  2          2015 307340     1500  2970       270      1470     52560    34900
##  3          2016 352880     1540  4090       460      1540     65760    46750
##  4          2017 323590     1450  3660       670      1510     62740    43410
##  5          2018 396450     1580  9820      1130      3430     99750    62460
##  6          2019 510850     1660  8450      3250      7890    152250   104170
##  7          2020 182870     1160  1280      1250      1470     30720    16860
##  8          2021 211450     3120  1840     23480     26920     10490    13110
##  9          2022 311580    39270  9210     36690     48070      9930    11280
## 10          2023 273220    34110  7530     15190      4460     17750    21640
## 11          2024 277910    20120  6400     18360     10340     36100    27980
## 12          2025  44750     3280  1850      1180       610      4670     4510
## # ℹ 5 more variables: Mexico <dbl>, `Dominican Republic` <dbl>, Other <dbl>,
## #   `El Salvador` <dbl>, Ecuador <dbl>
summary(detention)
##   Fiscal Year       Total           Colombia         India     
##  Min.   :2014   Min.   : 44750   Min.   : 1160   Min.   :1280  
##  1st Qu.:2017   1st Qu.:257778   1st Qu.: 1530   1st Qu.:2195  
##  Median :2020   Median :309460   Median : 1620   Median :3875  
##  Mean   :2020   Mean   :301552   Mean   : 9196   Mean   :4951  
##  3rd Qu.:2022   3rd Qu.:363773   3rd Qu.: 7490   3rd Qu.:7760  
##  Max.   :2025   Max.   :510850   Max.   :39270   Max.   :9820  
##    Venezuela         Nicaragua       Guatemala         Honduras     
##  Min.   :  270.0   Min.   :  610   Min.   :  4670   Min.   :  4510  
##  1st Qu.:  617.5   1st Qu.: 1500   1st Qu.: 15935   1st Qu.: 15922  
##  Median : 1215.0   Median : 2905   Median : 44330   Median : 31440  
##  Mean   : 8516.7   Mean   : 9174   Mean   : 51438   Mean   : 38648  
##  3rd Qu.:15982.5   3rd Qu.: 8502   3rd Qu.: 67955   3rd Qu.: 50678  
##  Max.   :36690.0   Max.   :48070   Max.   :152250   Max.   :104170  
##      Mexico       Dominican Republic     Other         El Salvador   
##  Min.   : 12240   Min.   :  940      Min.   : 11220   Min.   : 2240  
##  1st Qu.: 49683   1st Qu.: 2320      1st Qu.: 26668   1st Qu.: 8038  
##  Median :103975   Median : 2705      Median : 40715   Median :22140  
##  Mean   : 93670   Mean   : 3918      Mean   : 46902   Mean   :26733  
##  3rd Qu.:135905   3rd Qu.: 3760      3rd Qu.: 63115   3rd Qu.:42698  
##  Max.   :172560   Max.   :13130      Max.   :100720   Max.   :59930  
##     Ecuador     
##  Min.   : 2010  
##  1st Qu.: 2962  
##  Median : 4630  
##  Mean   : 8410  
##  3rd Qu.:13050  
##  Max.   :22940
plot(detention$`Fiscal Year`)

Technical Communication 2

The generic functions print(), summary(), and plot() were used on the detention dataset. They invoked class‑specific methods, enabling the data to be shown in a clear format, automatically calculating essential descriptive statistics, and visualizing it over fiscal years. This method mainly aims to simplify routine data exploration and offer a uniform interface for analysts handling various data structures.

Explore S3 vs. S4

# Create an S3 object
s3_detention <- list(
  dataset = detention,
  total_years = nrow(detention)
)

class(s3_detention) <- "detention_s3"

Demonstrate S3 Method Dispatch

# print S3 object
print(s3_detention)
## $dataset
## # A tibble: 12 × 13
##    `Fiscal Year`  Total Colombia India Venezuela Nicaragua Guatemala Honduras
##            <dbl>  <dbl>    <dbl> <dbl>     <dbl>     <dbl>     <dbl>    <dbl>
##  1          2014 425730     1560  2310       270      2380     74540    76710
##  2          2015 307340     1500  2970       270      1470     52560    34900
##  3          2016 352880     1540  4090       460      1540     65760    46750
##  4          2017 323590     1450  3660       670      1510     62740    43410
##  5          2018 396450     1580  9820      1130      3430     99750    62460
##  6          2019 510850     1660  8450      3250      7890    152250   104170
##  7          2020 182870     1160  1280      1250      1470     30720    16860
##  8          2021 211450     3120  1840     23480     26920     10490    13110
##  9          2022 311580    39270  9210     36690     48070      9930    11280
## 10          2023 273220    34110  7530     15190      4460     17750    21640
## 11          2024 277910    20120  6400     18360     10340     36100    27980
## 12          2025  44750     3280  1850      1180       610      4670     4510
## # ℹ 5 more variables: Mexico <dbl>, `Dominican Republic` <dbl>, Other <dbl>,
## #   `El Salvador` <dbl>, Ecuador <dbl>
## 
## $total_years
## [1] 12
## 
## attr(,"class")
## [1] "detention_s3"

Comparison of S3 and S4 Object

# Create an S4 class and object
setClass(
  "detention_s4",
  slots = c(
    year = "numeric",
    total = "numeric"
  )
)

# Create an object
s4_detention <- new(
  "detention_s4",
  year = 2024,
  total = 372000
)

# Set method for S4
setMethod(
  "show",
  "detention_s4",
  function(object) {
    cat("Fiscal Year:", object@year, "\n")
    cat("Detentions:", object@total, "\n")
  }
)

Demonstrate S4 Method Dispatch

# print S4 object
print(s4_detention)
## Fiscal Year: 2024 
## Detentions: 372000

Technical Communication 3

To investigate R’s object-oriented frameworks, I constructed both an S3 object and an S4 object derived from the ICE detention dataset. The S3 object employed an informal class assignment via class(), whereas the S4 object was formally specified with setClass(). I tested generic functions such as print() to illustrate method dispatch. The S4 approach offered a more robust structure through predefined slots and type validation.

Reproducibility checks

Defensive Programming in R

stopifnot(file.exists(file.path("data-raw", "ice_detention.csv")))
stopifnot(all(complete.cases(detention)))
stopifnot(nrow(detention) == 12)
stopifnot(ncol(detention) == 13)
stopifnot(all(
  c("Fiscal Year", "Total", "Colombia", "India", "Venezuela")
  %in% names(detention)
))

Benefit to the R community

Because R packages are viewed as the best method for packaging and sharing R code and data for reuse by others, particularly students and novice R programmers, this package addresses several issues. It shows how to employ devtools to install a new package straight from a GitHub repository. It also assists users in dividing functions into separate packages and offers experience in crafting machine‑readable metadata.

AI-use disclosure

I used AI to assist with writing and grammar. I verified the output by reviewing. I revised course material, and review the suggestion. I revised the typographical errors. I am responsible for the final code, analysis, and interpretation.

Submission checklist

[X] Repository has DESCRIPTION, NAMESPACE, LICENSE, R/, man/, and README.md

[X] DESCRIPTION lists you as author, plus a title, description, version, license, and all dependencies

[X] Every exported function has roxygen documentation with @param, @return, and @examples

[X] Optional: a vignette (long-form documentation). Not required, but encouraged

[X] At least one S3 or S4 class with a method

[X] devtools::check() returns 0 errors

[X] A classmate can run devtools::install_github(“yourname/yourpackage”) and library(yourpackage) successfully

[X] Blog post covers both the technical features and the benefit to the R community, and links to the GitHub repository

[X] Commit history shows your work over time

[X] README ends with an AI use statement (tools used or “none”, what for, what you wrote yourself)

[X] Canvas submission includes the GitHub link and the blog post link

Reproducibility information

sessionInfo()
## R version 4.6.1 (2026-06-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 10 x64 (build 19045)
## 
## Matrix products: default
##   LAPACK version 3.12.1
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8 
## [2] LC_CTYPE=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## time zone: America/New_York
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] lubridate_1.9.5 forcats_1.0.1   stringr_1.6.0   dplyr_1.2.1    
##  [5] purrr_1.2.2     readr_2.2.0     tidyr_1.3.2     tibble_3.3.1   
##  [9] tidyverse_2.0.0 ggplot2_4.0.3   testthat_3.3.2  roxygen2_8.1.1 
## [13] devtools_2.5.2  usethis_3.2.2  
## 
## loaded via a namespace (and not attached):
##  [1] gtable_0.3.6       xfun_0.60          bslib_0.12.0       lattice_0.23-1    
##  [5] tzdb_0.5.0         vctrs_0.7.3        tools_4.6.1        generics_0.1.4    
##  [9] parallel_4.6.1     pkgconfig_2.0.3    Matrix_1.7-5       RColorBrewer_1.1-3
## [13] S7_0.2.2           lifecycle_1.0.5    compiler_4.6.1     farver_2.1.2      
## [17] brio_1.1.5         htmltools_0.5.9    sass_0.4.10        yaml_2.3.12       
## [21] pillar_1.11.1      crayon_1.5.3       jquerylib_0.1.4    ellipsis_0.3.3    
## [25] cachem_1.1.0       sessioninfo_1.2.4  nlme_3.1-169       tidyselect_1.2.1  
## [29] digest_0.6.39      stringi_1.8.9      labeling_0.4.3     splines_4.6.1     
## [33] fastmap_1.2.0      grid_4.6.1         cli_3.6.6          magrittr_2.0.5    
## [37] pkgbuild_1.4.8     withr_3.0.3        scales_1.4.0       bit64_4.8.6       
## [41] timechange_0.4.0   rmarkdown_2.32     bit_4.6.0          otel_0.2.0        
## [45] hms_1.1.4          memoise_2.0.1      evaluate_1.0.5     knitr_1.51        
## [49] mgcv_1.9-4         rlang_1.3.0        glue_1.8.1         xml2_1.6.0        
## [53] pkgload_1.5.3      rstudioapi_0.19.0  vroom_1.7.1        jsonlite_2.0.0    
## [57] R6_2.6.1           fs_2.1.0

Validation package

Must finish with 0 errors

#devtools::check()

Prior to submission, the package undergoes a comprehensive suite of tests encompassing syntax verification, documentation validation, and integrity assessments via devtools::check(), which yields no errors, warnings, or notes.

── R CMD check results ──────────────────────────────────────────────────────────────────────────────────────────── finalprojects 0.1.0 ──── Duration: 1m 41.7s

0 errors ✔ | 0 warnings ✔ | 0 notes ✔