R Packages

Lecture 05

Dr. Colin Rundel

What are R packages?

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

Search path

To load a package we use library(pkg) which attachs the package’s namespace (functions, data, etc.) 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"      "otel"          
 [9] "utils"          "yaml"          
[11] "grDevices"      "Rcpp"          
[13] "stats"          "datasets"      
[15] "rmarkdown"      "knitr"         
[17] "methods"        "jsonlite"      
[19] "xfun"           "digest"        
[21] "rlang"          "base"          
[23] "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"           "otel"          
[25] "rlang"          "jsonlite"      
[27] "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 global 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"           "otel"          
[25] "rlang"          "jsonlite"      
[27] "datasets"      
dplyr::lag(1:3)
[1] NA  1  2
loadedNamespaces()
 [1] "vctrs"          "cli"           
 [3] "knitr"          "rlang"         
 [5] "xfun"           "otel"          
 [7] "forcats"        "generics"      
 [9] "jsonlite"       "glue"          
[11] "htmltools"      "methods"       
[13] "datasets"       "rmarkdown"     
[15] "evaluate"       "tibble"        
[17] "fastmap"        "yaml"          
[19] "lifecycle"      "utils"         
[21] "diffmatchpatch" "compiler"      
[23] "dplyr"          "Rcpp"          
[25] "pkgconfig"      "base"          
[27] "stats"          "graphics"      
[29] "digest"         "R6"            
[31] "tidyselect"     "pillar"        
[33] "magrittr"       "tools"         
[35] "grDevices"     
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")

Local install:

From the terminal,

R CMD install ./diffmatchpatch
R CMD install diffmatchpatch_0.1.0.tar.gz

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 Installation - Files

Package development

What follows is an opinionated introduction to package development,

  • this is not the only way to do things (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 Build > Document menu will process all source files and rebuild all Rds

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

Dependencies

The DESCRIPTION file also specifies package dependencies using the fields:

  • Depends - Packages that are attached when your package is attached. Use sparingly.

  • Imports - Packages your code uses. These are loaded but not attached. Access functions via pkg::fun(). This is where most dependencies belong.

  • Suggests - Packages used in examples, tests, or vignettes but not required for core functionality. Users can install the package without these.

usethis::use_package("dplyr")              # Adds to Imports
usethis::use_package("ggplot2", "Suggests") # Adds to Suggests

Package checking

devtools::check() (or R CMD check) validates your package against CRAN standards

  • Verifies package structure and metadata
  • Runs all documentation examples and tests
  • Builds and checks vignettes
  • Checks for other common problems

Results are reported as:

  • ERRORs - Must be fixed; package will not install
  • WARNINGs - Should be fixed; CRAN will reject submissions with warnings
  • NOTEs - Should be investigated; some are acceptable, many are not for CRAN
devtools::check()

The devtools workflow

The typical package development cycle:

Function Description
devtools::load_all() Load all package code (simulates installing and attaching)
devtools::document() Run roxygen2 to update man/ and NAMESPACE
devtools::test() Run tests in tests/
devtools::check() Run R CMD check on your package
devtools::build() Build a source tarball (.tar.gz)
devtools::install() Install the package locally

The most common workflow during development is:

  1. Edit code in R/
  2. load_all() to test changes interactively
  3. document() after updating roxygen comments
  4. check() before committing or submitting

Other details

Vignette

Long form documentation for your package that live in vignettes/, 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 vignettes/articles/ which is added to .Rbuildignore

Package data

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

Generally these files are made available by saving data objects into the data/ directory of your package. Two formats are supported:

  • .Rdata files created using save() (can contain multiple objects)

  • .rds files created using usethis::use_data(obj) which uses saveRDS() (one object per file, recommended)

  • 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 with 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.4 MB
library(nycflights13)
pryr::mem_used()
55.7 MB
invisible(flights)
pryr::mem_used()
96.4 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 nycflights13

  • 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.

pkgdown

pkgdown is a package that makes it easy to build a website for your R package directly from the source files.

  • Generates a polished website from your existing documentation

  • Converts man/ files to HTML reference pages

  • Renders vignettes and articles as website pages

  • Creates a searchable function reference

  • Automatically links to other packages and functions

  • Can be customized via a _pkgdown.yml file

usethis::use_pkgdown()
pkgdown::build_site()