R Packages

Lecture 05

Dr. Colin Rundel

What are R packages?

R packages are just a collection of files - R code, compiled code (C, C++, etc.), data, documentation, and others that live in your library path.

.libPaths()
[1] "/Users/rundel/Library/R/arm64/4.5/library"                           
[2] "/Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library"
dir(.libPaths())
  [1] "_backup"                     
  [2] "_build"                      
  [3] "_cache"                      
  [4] "abind"                       
  [5] "and"                         
  [6] "anytime"                     
  [7] "ape"                         
  [8] "archive"                     
  [9] "arrayhelpers"                
 [10] "arrow"                       
 [11] "AsioHeaders"                 
 [12] "askpass"                     
 [13] "assertthat"                  
 [14] "astsa"                       
 [15] "available"                   
 [16] "babelwhale"                  
 [17] "backports"                   
 [18] "BART"                        
 [19] "base"                        
 [20] "base64enc"                   
 [21] "BayesFactor"                 
 [22] "bayesplot"                   
 [23] "bcf"                         
 [24] "beeswarm"                    
 [25] "bench"                       
 [26] "berryFunctions"              
 [27] "BH"                          
 [28] "bigD"                        
 [29] "bit"                         
 [30] "bit64"                       
 [31] "bitops"                      
 [32] "blob"                        
 [33] "bonsai"                      
 [34] "bookdown"                    
 [35] "boot"                        
 [36] "bootstrap"                   
 [37] "brew"                        
 [38] "bridgesampling"              
 [39] "brio"                        
 [40] "brms"                        
 [41] "Brobdingnag"                 
 [42] "broom"                       
 [43] "broom.helpers"               
 [44] "broom.mixed"                 
 [45] "bs4Dash"                     
 [46] "bsicons"                     
 [47] "bslib"                       
 [48] "btw"                         
 [49] "cachem"                      
 [50] "callr"                       
 [51] "car"                         
 [52] "carData"                     
 [53] "cards"                       
 [54] "caret"                       
 [55] "carrier"                     
 [56] "caTools"                     
 [57] "cellranger"                  
 [58] "centiserve"                  
 [59] "checkmate"                   
 [60] "chromote"                    
 [61] "chron"                       
 [62] "circlize"                    
 [63] "class"                       
 [64] "classInt"                    
 [65] "cli"                         
 [66] "clipr"                       
 [67] "clisymbols"                  
 [68] "clock"                       
 [69] "clue"                        
 [70] "cluster"                     
 [71] "coda"                        
 [72] "codetools"                   
 [73] "collections"                 
 [74] "colorspace"                  
 [75] "colourpicker"                
 [76] "commonmark"                  
 [77] "compiler"                    
 [78] "confintr"                    
 [79] "conflicted"                  
 [80] "connectapi"                  
 [81] "contfrac"                    
 [82] "coreNLP"                     
 [83] "coro"                        
 [84] "corrplot"                    
 [85] "countdown"                   
 [86] "countrycode"                 
 [87] "covr"                        
 [88] "cowplot"                     
 [89] "cpp11"                       
 [90] "crancache"                   
 [91] "cranlike"                    
 [92] "crayon"                      
 [93] "credentials"                 
 [94] "crosstalk"                   
 [95] "crul"                        
 [96] "cubature"                    
 [97] "curl"                        
 [98] "cyclocomp"                   
 [99] "DAAG"                        
[100] "data.table"                  
[101] "datasauRus"                  
[102] "datasets"                    
[103] "datawizard"                  
[104] "dbarts"                      
[105] "DBI"                         
[106] "dbplyr"                      
[107] "debugme"                     
[108] "deepgp"                      
[109] "deldir"                      
[110] "DEoptimR"                    
[111] "Deriv"                       
[112] "desc"                        
[113] "deSolve"                     
[114] "devEMF"                      
[115] "devtools"                    
[116] "diagram"                     
[117] "dials"                       
[118] "DiceDesign"                  
[119] "diffmatchpatch"              
[120] "diffobj"                     
[121] "diffviewer"                  
[122] "digest"                      
[123] "distributional"              
[124] "dm"                          
[125] "doBy"                        
[126] "doFuture"                    
[127] "doMC"                        
[128] "doParallel"                  
[129] "dotCall64"                   
[130] "dotty"                       
[131] "downlit"                     
[132] "dplyr"                       
[133] "DT"                          
[134] "dtplyr"                      
[135] "dtt"                         
[136] "duckdb"                      
[137] "duckplyr"                    
[138] "dygraphs"                    
[139] "dynparam"                    
[140] "dynutils"                    
[141] "dynwrap"                     
[142] "e1071"                       
[143] "echarts4r"                   
[144] "editData"                    
[145] "ellipsis"                    
[146] "elliptic"                    
[147] "ellmer"                      
[148] "evaluate"                    
[149] "expm"                        
[150] "extraDistr"                  
[151] "extrafont"                   
[152] "extrafontdb"                 
[153] "f1dataR"                     
[154] "fable"                       
[155] "fable.prophet"               
[156] "fabletools"                  
[157] "fansi"                       
[158] "farver"                      
[159] "fastmap"                     
[160] "feasts"                      
[161] "fields"                      
[162] "filelock"                    
[163] "flexiblas"                   
[164] "flextable"                   
[165] "float"                       
[166] "FNN"                         
[167] "fontawesome"                 
[168] "fontBitstreamVera"           
[169] "fontLiberation"              
[170] "fontquiver"                  
[171] "forcats"                     
[172] "foreach"                     
[173] "forecast"                    
[174] "foreign"                     
[175] "formatR"                     
[176] "formattable"                 
[177] "Formula"                     
[178] "fracdiff"                    
[179] "fredr"                       
[180] "fresh"                       
[181] "fs"                          
[182] "furrr"                       
[183] "future"                      
[184] "future.apply"                
[185] "gargle"                      
[186] "gdtools"                     
[187] "generics"                    
[188] "geometry"                    
[189] "geoR"                        
[190] "geosphere"                   
[191] "gert"                        
[192] "gfonts"                      
[193] "GGally"                      
[194] "gganimate"                   
[195] "ggbeeswarm"                  
[196] "ggcorrplot"                  
[197] "ggdist"                      
[198] "ggExtra"                     
[199] "ggfittext"                   
[200] "ggforce"                     
[201] "ggfun"                       
[202] "ggimage"                     
[203] "gginnards"                   
[204] "ggiraph"                     
[205] "ggplot2"                     
[206] "ggplotify"                   
[207] "ggpmisc"                     
[208] "ggpp"                        
[209] "ggpubr"                      
[210] "ggrepel"                     
[211] "ggridges"                    
[212] "ggsci"                       
[213] "ggsignif"                    
[214] "ggstats"                     
[215] "ggthemes"                    
[216] "gh"                          
[217] "ghclass"                     
[218] "gifski"                      
[219] "gitcreds"                    
[220] "glarma"                      
[221] "glmnet"                      
[222] "GlobalOptions"               
[223] "globals"                     
[224] "glue"                        
[225] "gmailr"                      
[226] "gmp"                         
[227] "googledrive"                 
[228] "googlesheets4"               
[229] "gower"                       
[230] "GPArotation"                 
[231] "GPfit"                       
[232] "GpGp"                        
[233] "gptstudio"                   
[234] "graphics"                    
[235] "grDevices"                   
[236] "grid"                        
[237] "gridExtra"                   
[238] "gridGraphics"                
[239] "gridtext"                    
[240] "gsubfn"                      
[241] "gt"                          
[242] "gtable"                      
[243] "gtools"                      
[244] "hardhat"                     
[245] "haven"                       
[246] "hayalbaz"                    
[247] "here"                        
[248] "hexbin"                      
[249] "hexSticker"                  
[250] "highlite"                    
[251] "highr"                       
[252] "histoslider"                 
[253] "Hmisc"                       
[254] "hms"                         
[255] "hrbrthemes"                  
[256] "htmlTable"                   
[257] "htmltools"                   
[258] "htmlwidgets"                 
[259] "httpcode"                    
[260] "httpuv"                      
[261] "httr"                        
[262] "httr2"                       
[263] "hypergeo"                    
[264] "ids"                         
[265] "igraph"                      
[266] "infer"                       
[267] "ini"                         
[268] "inline"                      
[269] "insight"                     
[270] "installr"                    
[271] "interp"                      
[272] "ipred"                       
[273] "isoband"                     
[274] "iterators"                   
[275] "janeaustenr"                 
[276] "janitor"                     
[277] "job"                         
[278] "jose"                        
[279] "jpeg"                        
[280] "jquerylib"                   
[281] "jsonlite"                    
[282] "juicyjuice"                  
[283] "kableExtra"                  
[284] "KernSmooth"                  
[285] "knitr"                       
[286] "labeling"                    
[287] "labelled"                    
[288] "languageserver"              
[289] "later"                       
[290] "latex2exp"                   
[291] "lattice"                     
[292] "latticeExtra"                
[293] "lava"                        
[294] "lazyeval"                    
[295] "leaflet"                     
[296] "leaflet.extras"              
[297] "leaflet.extras2"             
[298] "leaflet.providers"           
[299] "leafpop"                     
[300] "LearnBayes"                  
[301] "learnr"                      
[302] "lgr"                         
[303] "lhs"                         
[304] "lifecycle"                   
[305] "linprog"                     
[306] "lintr"                       
[307] "listenv"                     
[308] "litedown"                    
[309] "lme4"                        
[310] "lmodel2"                     
[311] "lmtest"                      
[312] "lobstr"                      
[313] "logger"                      
[314] "loo"                         
[315] "lookup"                      
[316] "lorem"                       
[317] "lpSolve"                     
[318] "lubridate"                   
[319] "lwgeom"                      
[320] "magic"                       
[321] "magick"                      
[322] "magrittr"                    
[323] "maps"                        
[324] "markdown"                    
[325] "markermd"                    
[326] "marquee"                     
[327] "MASS"                        
[328] "Matrix"                      
[329] "MatrixExtra"                 
[330] "MatrixModels"                
[331] "matrixStats"                 
[332] "maxLik"                      
[333] "mc2d"                        
[334] "mclust"                      
[335] "mcptools"                    
[336] "md4r"                        
[337] "memoise"                     
[338] "methods"                     
[339] "Metrics"                     
[340] "mgcv"                        
[341] "microbenchmark"              
[342] "mime"                        
[343] "miniUI"                      
[344] "minqa"                       
[345] "miscTools"                   
[346] "mitools"                     
[347] "mlapi"                       
[348] "mlbench"                     
[349] "mlbplotR"                    
[350] "mnormt"                      
[351] "mockery"                     
[352] "modeldata"                   
[353] "modelenv"                    
[354] "ModelMetrics"                
[355] "modelr"                      
[356] "modeltools"                  
[357] "moonBook"                    
[358] "multcomp"                    
[359] "multcompView"                
[360] "munsell"                     
[361] "mvtnorm"                     
[362] "nabor"                       
[363] "naniar"                      
[364] "nanonext"                    
[365] "nanoparquet"                 
[366] "nleqslv"                     
[367] "nlme"                        
[368] "nloptr"                      
[369] "NLP"                         
[370] "nnet"                        
[371] "nngeo"                       
[372] "norm"                        
[373] "nortest"                     
[374] "numDeriv"                    
[375] "nycflights13"                
[376] "officer"                     
[377] "openssl"                     
[378] "openxlsx"                    
[379] "oskeyring"                   
[380] "packrat"                     
[381] "padr"                        
[382] "pagedown"                    
[383] "pak"                         
[384] "palmerpenguins"              
[385] "pander"                      
[386] "pandoc"                      
[387] "parallel"                    
[388] "parallelly"                  
[389] "parsedate"                   
[390] "parsermd"                    
[391] "parsnip"                     
[392] "patchwork"                   
[393] "paws"                        
[394] "paws.analytics"              
[395] "paws.application.integration"
[396] "paws.common"                 
[397] "paws.compute"                
[398] "paws.cost.management"        
[399] "paws.customer.engagement"    
[400] "paws.database"               
[401] "paws.developer.tools"        
[402] "paws.end.user.computing"     
[403] "paws.machine.learning"       
[404] "paws.management"             
[405] "paws.networking"             
[406] "paws.security.identity"      
[407] "paws.storage"                
[408] "pbapply"                     
[409] "pbkrtest"                    
[410] "pcaPP"                       
[411] "pdftools"                    
[412] "pdist"                       
[413] "PerformanceAnalytics"        
[414] "pillar"                      
[415] "pingr"                       
[416] "pkgbuild"                    
[417] "pkgcache"                    
[418] "pkgconfig"                   
[419] "pkgdepends"                  
[420] "pkgdown"                     
[421] "pkgload"                     
[422] "pkgsearch"                   
[423] "PKI"                         
[424] "plogr"                       
[425] "plotly"                      
[426] "plumber"                     
[427] "plyr"                        
[428] "png"                         
[429] "polite"                      
[430] "polyclip"                    
[431] "polynom"                     
[432] "posterior"                   
[433] "pracma"                      
[434] "praise"                      
[435] "prettyunits"                 
[436] "PrevMap"                     
[437] "prismatic"                   
[438] "pROC"                        
[439] "processx"                    
[440] "prodlim"                     
[441] "profmem"                     
[442] "profvis"                     
[443] "progress"                    
[444] "progressr"                   
[445] "promises"                    
[446] "prophet"                     
[447] "proto"                       
[448] "proxy"                       
[449] "proxyC"                      
[450] "pryr"                        
[451] "ps"                          
[452] "pscl"                        
[453] "psych"                       
[454] "purrr"                       
[455] "pyinit"                      
[456] "qpdf"                        
[457] "qs"                          
[458] "quadprog"                    
[459] "qualtRics"                   
[460] "quantmod"                    
[461] "quantreg"                    
[462] "quarto"                      
[463] "queryparser"                 
[464] "QuickJSR"                    
[465] "quickr"                      
[466] "R.cache"                     
[467] "R.methodsS3"                 
[468] "R.oo"                        
[469] "R.utils"                     
[470] "R6"                          
[471] "ragg"                        
[472] "randomForest"                
[473] "randomNames"                 
[474] "ranger"                      
[475] "RANN"                        
[476] "RApiSerialize"               
[477] "rappdirs"                    
[478] "rapportools"                 
[479] "raster"                      
[480] "rasterVis"                   
[481] "ratelimitr"                  
[482] "rbibutils"                   
[483] "rcmdcheck"                   
[484] "RColorBrewer"                
[485] "Rcpp"                        
[486] "RcppArmadillo"               
[487] "RcppEigen"                   
[488] "RcppInt64"                   
[489] "RcppParallel"                
[490] "RcppProgress"                
[491] "RcppRoll"                    
[492] "RcppTOML"                    
[493] "RCurl"                       
[494] "Rdpack"                      
[495] "reactable"                   
[496] "reactlog"                    
[497] "reactR"                      
[498] "readr"                       
[499] "readxl"                      
[500] "recipes"                     
[501] "reclin2"                     
[502] "reformulas"                  
[503] "registry"                    
[504] "rematch"                     
[505] "rematch2"                    
[506] "remotes"                     
[507] "renderthis"                  
[508] "renv"                        
[509] "repr"                        
[510] "reprex"                      
[511] "repurrrsive"                 
[512] "reshape"                     
[513] "reshape2"                    
[514] "reticulate"                  
[515] "revdepcheck"                 
[516] "rex"                         
[517] "RhpcBLASctl"                 
[518] "rhub"                        
[519] "rio"                         
[520] "rjags"                       
[521] "rJava"                       
[522] "rjson"                       
[523] "rlang"                       
[524] "rmarkdown"                   
[525] "Rmpfr"                       
[526] "rnaturalearth"               
[527] "rnaturalearthdata"           
[528] "rnaturalearthhires"          
[529] "robotstxt"                   
[530] "RobStatTM"                   
[531] "robustbase"                  
[532] "ROI"                         
[533] "roxygen2"                    
[534] "rpart"                       
[535] "rpart.plot"                  
[536] "rprojroot"                   
[537] "rrcov"                       
[538] "rrtable"                     
[539] "rsample"                     
[540] "rsconnect"                   
[541] "rsparse"                     
[542] "RSQLite"                     
[543] "rstan"                       
[544] "rstanarm"                    
[545] "rstantools"                  
[546] "rstatix"                     
[547] "rstudioapi"                  
[548] "Rttf2pt1"                    
[549] "rversions"                   
[550] "rvest"                       
[551] "rvg"                         
[552] "s2"                          
[553] "S7"                          
[554] "sandwich"                    
[555] "sass"                        
[556] "scales"                      
[557] "selectr"                     
[558] "servr"                       
[559] "sessioninfo"                 
[560] "sf"                          
[561] "sfd"                         
[562] "sfdep"                       
[563] "shades"                      
[564] "shape"                       
[565] "shiny"                       
[566] "shiny.blueprint"             
[567] "shiny.i18n"                  
[568] "shiny.react"                 
[569] "shinyBS"                     
[570] "shinybusy"                   
[571] "shinycssloaders"             
[572] "shinydashboard"              
[573] "shinyFeedback"               
[574] "shinyjs"                     
[575] "shinylive"                   
[576] "shinystan"                   
[577] "shinytest2"                  
[578] "shinythemes"                 
[579] "shinyvalidate"               
[580] "shinyWidgets"                
[581] "showimage"                   
[582] "showtext"                    
[583] "showtextdb"                  
[584] "sjlabelled"                  
[585] "sjmisc"                      
[586] "skimr"                       
[587] "slam"                        
[588] "slickR"                      
[589] "slider"                      
[590] "snakecase"                   
[591] "SnowballC"                   
[592] "snowflakeauth"               
[593] "sodium"                      
[594] "sourcetools"                 
[595] "sp"                          
[596] "spam"                        
[597] "spaMM"                       
[598] "SparseM"                     
[599] "sparsevctrs"                 
[600] "spatial"                     
[601] "spatialreg"                  
[602] "spBayes"                     
[603] "spData"                      
[604] "spdep"                       
[605] "spiderbar"                   
[606] "splancs"                     
[607] "splines"                     
[608] "splus2R"                     
[609] "spNNGP"                      
[610] "sportyR"                     
[611] "spotifyr"                    
[612] "sqldf"                       
[613] "SQUAREM"                     
[614] "SSEparser"                   
[615] "StanHeaders"                 
[616] "stars"                       
[617] "starsExtra"                  
[618] "statebins"                   
[619] "StatMatch"                   
[620] "stats"                       
[621] "stats4"                      
[622] "statsr"                      
[623] "stringdist"                  
[624] "stringfish"                  
[625] "stringi"                     
[626] "stringr"                     
[627] "styler"                      
[628] "summarytools"                
[629] "superml"                     
[630] "survey"                      
[631] "survival"                    
[632] "svglite"                     
[633] "svUnit"                      
[634] "swagger"                     
[635] "sys"                         
[636] "sysfonts"                    
[637] "systemfonts"                 
[638] "syuzhet"                     
[639] "tailor"                      
[640] "taylor"                      
[641] "tcltk"                       
[642] "tensorA"                     
[643] "terra"                       
[644] "testthat"                    
[645] "text2vec"                    
[646] "textshape"                   
[647] "textshaping"                 
[648] "textutils"                   
[649] "TH.data"                     
[650] "thematic"                    
[651] "threejs"                     
[652] "tibble"                      
[653] "tidybayes"                   
[654] "tidymodels"                  
[655] "tidyquant"                   
[656] "tidyquery"                   
[657] "tidyr"                       
[658] "tidyselect"                  
[659] "tidytext"                    
[660] "tidyverse"                   
[661] "tigris"                      
[662] "timechange"                  
[663] "timeDate"                    
[664] "timetk"                      
[665] "tinytex"                     
[666] "tm"                          
[667] "tokenizers"                  
[668] "tools"                       
[669] "toOrdinal"                   
[670] "topicmodels"                 
[671] "transformr"                  
[672] "translations"                
[673] "treesitter.r"                
[674] "triebeard"                   
[675] "truncnorm"                   
[676] "tseries"                     
[677] "tsfeatures"                  
[678] "tsibble"                     
[679] "tsibbledata"                 
[680] "TTR"                         
[681] "tune"                        
[682] "tutorial.helpers"            
[683] "tweenr"                      
[684] "tzdb"                        
[685] "udpipe"                      
[686] "uni"                         
[687] "units"                       
[688] "unvotes"                     
[689] "UpSetR"                      
[690] "urca"                        
[691] "urlchecker"                  
[692] "urltools"                    
[693] "usethis"                     
[694] "usmap"                       
[695] "usmapdata"                   
[696] "utf8"                        
[697] "utf8splain"                  
[698] "utils"                       
[699] "uuid"                        
[700] "V8"                          
[701] "vcd"                         
[702] "vctrs"                       
[703] "vipor"                       
[704] "viridis"                     
[705] "viridisLite"                 
[706] "visdat"                      
[707] "vroom"                       
[708] "waiter"                      
[709] "waldo"                       
[710] "warp"                        
[711] "webr"                        
[712] "webshot"                     
[713] "webshot2"                    
[714] "websocket"                   
[715] "webutils"                    
[716] "whisker"                     
[717] "whoami"                      
[718] "withr"                       
[719] "wk"                          
[720] "wordcloud"                   
[721] "wordcloud2"                  
[722] "workflows"                   
[723] "workflowsets"                
[724] "writexl"                     
[725] "xaringan"                    
[726] "xaringanExtra"               
[727] "xfun"                        
[728] "xkcd"                        
[729] "XML"                         
[730] "xml2"                        
[731] "xmlparsedata"                
[732] "xopen"                       
[733] "xtable"                      
[734] "xts"                         
[735] "yaml"                        
[736] "yardstick"                   
[737] "yesno"                       
[738] "yulab.utils"                 
[739] "zip"                         
[740] "zoo"                         
[741] "ztable"                      

Search path

When you run library(pkg) the functions (and objects) in the package’s namespace are attached to the global search path.

search()
[1] ".GlobalEnv"        "package:stats"    
[3] "package:graphics"  "package:grDevices"
[5] "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"        
[9] "package:base"     
library(diffmatchpatch)
search()
 [1] ".GlobalEnv"            
 [2] "package:diffmatchpatch"
 [3] "package:stats"         
 [4] "package:graphics"      
 [5] "package:grDevices"     
 [6] "package:utils"         
 [7] "package:datasets"      
 [8] "package:methods"       
 [9] "Autoloads"             
[10] "package:base"          

Loading vs attaching

If you do not want to attach a package you can directly load the package with requireNamespace().

loadedNamespaces()
 [1] "compiler"       "fastmap"       
 [3] "cli"            "graphics"      
 [5] "diffmatchpatch" "tools"         
 [7] "htmltools"      "utils"         
 [9] "yaml"           "grDevices"     
[11] "Rcpp"           "stats"         
[13] "datasets"       "rmarkdown"     
[15] "knitr"          "methods"       
[17] "jsonlite"       "xfun"          
[19] "digest"         "rlang"         
[21] "base"           "evaluate"      
requireNamespace("forcats")
Loading required namespace: forcats
loadedNamespaces()
 [1] "digest"         "methods"       
 [3] "diffmatchpatch" "fastmap"       
 [5] "xfun"           "magrittr"      
 [7] "glue"           "knitr"         
 [9] "htmltools"      "rmarkdown"     
[11] "lifecycle"      "utils"         
[13] "cli"            "graphics"      
[15] "grDevices"      "stats"         
[17] "compiler"       "forcats"       
[19] "base"           "tools"         
[21] "evaluate"       "Rcpp"          
[23] "yaml"           "rlang"         
[25] "jsonlite"       "datasets"      
search()
 [1] ".GlobalEnv"            
 [2] "package:diffmatchpatch"
 [3] "package:stats"         
 [4] "package:graphics"      
 [5] "package:grDevices"     
 [6] "package:utils"         
 [7] "package:datasets"      
 [8] "package:methods"       
 [9] "Autoloads"             
[10] "package:base"          

Automatic loading

Using a package function via :: will automatically load the package (and its dependencies) but not attach it to the search path.

loadedNamespaces()
 [1] "digest"         "methods"       
 [3] "diffmatchpatch" "fastmap"       
 [5] "xfun"           "magrittr"      
 [7] "glue"           "knitr"         
 [9] "htmltools"      "rmarkdown"     
[11] "lifecycle"      "utils"         
[13] "cli"            "graphics"      
[15] "grDevices"      "stats"         
[17] "compiler"       "forcats"       
[19] "base"           "tools"         
[21] "evaluate"       "Rcpp"          
[23] "yaml"           "rlang"         
[25] "jsonlite"       "datasets"      
dplyr::lag(1:3)
[1] NA  1  2
loadedNamespaces()
 [1] "digest"         "methods"       
 [3] "R6"             "diffmatchpatch"
 [5] "fastmap"        "tidyselect"    
 [7] "xfun"           "magrittr"      
 [9] "glue"           "tibble"        
[11] "knitr"          "pkgconfig"     
[13] "htmltools"      "generics"      
[15] "dplyr"          "rmarkdown"     
[17] "lifecycle"      "utils"         
[19] "cli"            "vctrs"         
[21] "graphics"       "grDevices"     
[23] "stats"          "compiler"      
[25] "forcats"        "base"          
[27] "tools"          "pillar"        
[29] "evaluate"       "Rcpp"          
[31] "yaml"           "rlang"         
[33] "jsonlite"       "datasets"      
search()
 [1] ".GlobalEnv"            
 [2] "package:diffmatchpatch"
 [3] "package:stats"         
 [4] "package:graphics"      
 [5] "package:grDevices"     
 [6] "package:utils"         
 [7] "package:datasets"      
 [8] "package:methods"       
 [9] "Autoloads"             
[10] "package:base"          

Where do R packages come from?

Generally from somewhere on the internet, most commonly from CRAN or GitHub, the methods for installing from these locations are slightly different.

CRAN:

install.packages("diffmatchpatch")

GitHub:

remotes::install_github("rundel/diffmatchpatch")

there is one other method that comes up (particularly around package development), which is to install a package from local file(s).

Local install:

From the terminal,

R CMD install diffmatchpatch_0.1.0.tar.gz

or from R,

devtools::install("diffmatchpatch_0.1.0.tar.gz")

What is CRAN

The Comprehensive R Archive Network is the central repository of R packages.

  • Maintained by the R Foundation and run by a team of volunteers, ~23k packages

  • Contains all current versions of released packages as well as previous releases (including archived packages)

  • Similar in spirit to Perl’s CPAN, TeX’s CTAN, and Python’s PyPI

  • Some important features:

    • All submissions are reviewed by humans + automated checks

    • Strictly enforced submission policies and package requirements

    • All packages must be actively maintained and support upstream and downstream changes

Structure of an R Package



Core components

  • DESCRIPTION - file containing package metadata (e.g. package name, description, version, license, and author details). Also specifies package dependencies.

  • NAMESPACE - details which functions and objects are exported by your package.

  • R/ - contains all R script files (.R) implementing package

  • man/ - contains all R documentation files (.Rd)

Optional components

The following components are optional, but quite common:

  • tests/ - contains unit tests (.R scripts)

  • src/ - contains code to be compiled (usually C / C++)

  • data/ - contains example data sets (.rds or .rda)

  • inst/ - contains files that will be copied to the package’s top-level directory when it is installed (e.g. C/C++ headers, examples or data files that don’t belong in data/)

  • vignettes/ - contains long form documentation, can be static (.pdf or .html) or literate documents (e.g. .qmd, .Rmd or .Rnw)

Package contents

Source Package

fs::dir_tree("~/Desktop/Projects/diffmatchpatch/")
~/Desktop/Projects/diffmatchpatch/
├── DESCRIPTION
├── LICENSE.md
├── NAMESPACE
├── NEWS.md
├── R
│   ├── RcppExports.R
│   ├── diff.R
│   ├── diffmatchpatch-package.R
│   ├── match.R
│   ├── options.R
│   ├── patch.R
│   └── print.R
├── README.Rmd
├── README.md
├── cran-comments.md
├── diffmatchpatch.Rproj
├── inst
│   └── include
│       └── diff_match_patch.h
├── man
│   ├── diff.Rd
│   ├── dmp_options.Rd
│   ├── match.Rd
│   └── patch.Rd
└── src
    ├── Makevars
    ├── Makevars.win
    ├── RcppExports.cpp
    ├── RcppExports.o
    ├── common.h
    ├── diff.cpp
    ├── diff.o
    ├── diffmatchpatch.so
    ├── match.cpp
    ├── match.o
    ├── options.cpp
    ├── options.o
    ├── patch.cpp
    └── patch.o

Installed Package

fs::dir_tree(system.file(package="diffmatchpatch"))
/Users/rundel/Library/R/arm64/4.5/library/diffmatchpatch
├── DESCRIPTION
├── INDEX
├── Meta
│   ├── Rd.rds
│   ├── features.rds
│   ├── hsearch.rds
│   ├── links.rds
│   ├── nsInfo.rds
│   └── package.rds
├── NAMESPACE
├── NEWS.md
├── R
│   ├── diffmatchpatch
│   ├── diffmatchpatch.rdb
│   └── diffmatchpatch.rdx
├── help
│   ├── AnIndex
│   ├── aliases.rds
│   ├── diffmatchpatch.rdb
│   ├── diffmatchpatch.rdx
│   └── paths.rds
├── html
│   ├── 00Index.html
│   └── R.css
├── include
│   └── diff_match_patch.h
└── libs
    └── diffmatchpatch.so

Package Installation

Package Installion - Files

Package development

What follows is an opinionated introduction to package development,

  • this is not the only way to do thing (none of the following tools are required)

  • We strongly recommend using:

    • RStudio
    • RStudio projects
    • GitHub
    • usethis
    • roxygen2
  • Read and follow along with R Packages (2e) - Chapter 1 - “The Whole Game”

usethis

This is an immensely useful package for automating all kinds of routine (and tedious) tasks within R

  • Tools for managing git and GitHub configuration

  • Tools for managing collaboration on GitHub via pull requests (see pr_*())

  • Tools for creating and configuring packages

  • Tools for configuring your R environment (e.g. .Rprofile and .Renviron)

  • and much much more

Live demo
Building a Package

Start your package

Rather than having to remember all of the necessary pieces and their format, usethis can help you bootstrap your package development process.

usethis::create_package()

Choosing a license

An important early step in developing a package is choosing a license - this is not trivial but is important to do early on, particularly if collaborating with others.

There are many resources available to help you choose a license, including:

Documentation

All R packages are expected to have documentation for all exported functions and data sets (this is a CRAN requirement). This documentation is stored as .Rd files in the man/ directory.

  • The Rd format is a markup language that is loosely based on LaTeX

  • Rd files are processed into LaTeX, HTML, and plain text when building the package

  • All packages need Rd files, that doesn’t mean you need to write Rd

Roxygen2

The premise of roxygen2 is simple: describe your functions in comments next to their definitions and roxygen2 will process your source code and comments to automatically generate .Rd files in man/, NAMESPACE, and, if needed, the Collate field in DESCRIPTION.

  • roxygen uses special comment lines prefixed with #'

  • roxygen specific command have the format @cmd and mostly match Rd commands

  • devtools::document() or menu Build > Document with reprocess all source files and rebuild all Rds

  • usethis::create_package() with roxygen = TRUE will initialize your package to use roxygen (default behavior)

Package vigenette(s)

Vignette

Long form documentation for your package that live in vignette/, use browseVignette(pkg) to see a package’s vignettes.

  • Not required, but adds a lot of value to a package

  • Generally these are literate documents (.Rmd, .Rnw) that are compiled to .html or .pdf when the package is built.

  • Built packages retain the rendered document, the source document, and all source code

    • vignette("colwise", package = "dplyr") opens rendered version

    • edit(vignette("colwise", package = "dplyr")) opens code chunks

  • Use usethis::use_vignette() to create a RMarkdown vignette template

Articles

These are an un-official extension to vignettes where package authors wish to include additional long form documentation that is included in their pkgdown site but not in the package (usually for space reasons).

  • Use usethis::use_article() to create

  • Files are added to vignette/articles/ which is added to .Rbuildignore

Package data

Exported data

Many packages contain sample data (e.g. nycflights13, babynames, etc.)

Generally these files are made available by saving a single data object as an .Rdata file (using save()) into the data/ directory of your package.

  • An easy option is to use usethis::use_data(obj) to create the necessary file(s)

  • Data is usually compressed, for large data sets it may be worth trying different options (there is a 5 Mb package size limit on CRAN)

  • Exported data must be documented (possible via roxygen)

Lazy data

By default when attaching a package all of that packages data is loaded - however if LazyData: true is set in the packages’ DESCRIPTION then data is only loaded when used.

pryr::mem_used()
55 MB
library(nycflights13)
pryr::mem_used()
55.2 MB
invisible(flights)
pryr::mem_used()
95.9 MB

If you use usethis::use_data() this option will be set in DESCRIPTION automatically.

Raw data

When published a package should generally only contain the final data set, but it is important that the process to generate the data is documented as well as any necessary preliminary data.

  • These can live any where but the general suggestion is to create a data-raw/ directory which is included in .Rbuildignore

  • data-raw/ then contain scripts, data files, and anything else needed to generate the final object

  • See examples babynames or nycflights

  • Use usethis::use_data_raw() to create and ignore the data-raw/ directory.

Internal data

If you have data that you want to have access to from within the package but not exported then it needs to live in a special Rdata object located at R/sysdata.rda.

  • Can be created using usethis::use_data(obj1, obj2, internal = TRUE)

  • Each call to the above will overwrite, so needs to include all objects

  • Not necessary for small data frames and similar objects - just create in a script. Use when you want the object to be compressed.

  • Example nflplotR which contains team logos and colors for NFL teams.

Raw data files

If you want to include raw data files (e.g .csv, shapefiles, etc.) there are generally placed in inst/ (or a nested folder) so that they are installed with the package.

  • Accessed using system.file("dir", package = "package") after install

  • Use folders to keep things organized, Hadley recommends and uses inst/extdata/

  • Example sf