Global environment

Packages and environments

  • Packacges use namespaces as spaces for names
    • We can think of a namespaces as a box that containts the package
# exported functions of stats
getNamespaceExports("stats")
##   [1] "confint.default"      "mahalanobis"          "optimize"            
##   [4] "hat"                  "Box.test"             "reorder"             
##   [7] "phyper"               "ar.mle"               "rhyper"              
##  [10] "contr.SAS"            "na.exclude"           "qgeom"               
##  [13] "is.ts"                "plogis"               "drop.terms"          
##  [16] "rlogis"               "convolve"             "ts.intersect"        
##  [19] "KalmanSmooth"         "ts.union"             "smoothEnds"          
##  [22] "is.tskernel"          "as.formula"           "dexp"                
##  [25] "inverse.gaussian"     "na.contiguous"        "line"                
##  [28] "dgeom"                "qbirthday"            "confint.lm"          
##  [31] "cophenetic"           "var.test"             "diffinv"             
##  [34] "ar"                   "dummy.coef"           "cooks.distance"      
##  [37] "density"              "ptukey"               "as.dist"             
##  [40] "drop1"                "rbeta"                "fligner.test"        
##  [43] "naprint"              "qqnorm"               "is.stepfun"          
##  [46] "lsfit"                "mad"                  "shapiro.test"        
##  [49] "qqplot"               "eff.aovlist"          "runif"               
##  [52] "isoreg"               "profile"              "is.leaf"             
##  [55] "dchisq"               "contr.poly"           "stepfun"             
##  [58] "quasipoisson"         "na.omit"              "pnbinom"             
##  [61] "ppois"                "model.matrix.default" "family"              
##  [64] "plot.ecdf"            "cor.test"             "pchisq"              
##  [67] "rchisq"               "na.fail"              "heatmap"             
##  [70] "rmultinom"            "power.t.test"         "qweibull"            
##  [73] "complete.cases"       "loess.control"        "qnbinom"             
##  [76] "df"                   "tsp<-"                "rnorm"               
##  [79] "addmargins"           "asOneSidedFormula"    "Pair"                
##  [82] "nlm"                  "covratio"             "C"                   
##  [85] "as.stepfun"           "D"                    "ar.burg"             
##  [88] "cov2cor"              "pgeom"                "chisq.test"          
##  [91] "p.adjust"             "nls"                  "integrate"           
##  [94] "fivenum"              "weighted.mean"        "rweibull"            
##  [97] "qqline"               "as.dendrogram"        "runmed"              
## [100] "aov"                  "dt"                   "influence"           
## [103] "rnbinom"              "coefficients"         "tsp"                 
## [106] "dfbeta"               "hasTsp"               "dbinom"              
## [109] "wilcox.test"          "scatter.smooth"       "start"               
## [112] "delete.response"      "qsignrank"            "is.mts"              
## [115] ".getXlevels"          "BIC"                  "ks.test"             
## [118] ".nknots.smspl"        "order.dendrogram"     "SSD"                 
## [121] "HoltWinters"          "qbeta"                "pbinom"              
## [124] "effects"              "rbinom"               "monthplot"           
## [127] "acf2AR"               "splinefunH"           "splinefun"           
## [130] "qunif"                "nls.control"          "dbeta"               
## [133] "influence.measures"   "as.ts"                "prop.trend.test"     
## [136] "summary.glm"          "get_all_vars"         "preplot"             
## [139] "mood.test"            "dunif"                "vcov"                
## [142] "glm.control"          "ar.ols"               "qgamma"              
## [145] "dendrapply"           "arima0.diag"          "dnbinom"             
## [148] "qnorm"                "contrasts<-"          "SSbiexp"             
## [151] "poisson.test"         "add.scope"            "plot.spec.phase"     
## [154] "dlnorm"               "makeARIMA"            "tsSmooth"            
## [157] "dnorm"                "nobs"                 "knots"               
## [160] "fitted"               "spline"               "symnum"              
## [163] "prcomp"               "friedman.test"        "KalmanForecast"      
## [166] "aggregate.data.frame" "plot.spec.coherency"  "frequency"           
## [169] "decompose"            "dsignrank"            "pcauchy"             
## [172] "dist"                 "SSmicmen"             "predict"             
## [175] "lag.plot"             "plnorm"               "write.ftable"        
## [178] "factanal"             "resid"                "rlnorm"              
## [181] "rstandard"            "plot.ts"              "optim"               
## [184] "glm.fit"              "predict.lm"           "dmultinom"           
## [187] "getCall"              "ansari.test"          "loadings"            
## [190] "NLSstAsymptotic"      "window<-"             "residuals.glm"       
## [193] "window"               "pbeta"                "pairwise.t.test"     
## [196] "mantelhaen.test"      "aggregate"            "qcauchy"             
## [199] "loess.smooth"         "predict.glm"          "extractAIC"          
## [202] "punif"                "approxfun"            "napredict"           
## [205] "weights"              "quasibinomial"        "SSweibull"           
## [208] "ave"                  "ARMAacf"              "bw.ucv"              
## [211] "estVar"               "cor"                  "update.formula"      
## [214] "pbirthday"            "se.contrast"          "alias"               
## [217] "rcauchy"              "cov"                  "case.names"          
## [220] "ls.print"             "nlminb"               "TukeyHSD"            
## [223] "hatvalues"            "contr.sum"            "ppoints"             
## [226] "filter"               "deviance"             "KalmanRun"           
## [229] "pnorm"                "lag"                  "ar.yw"               
## [232] "lm"                   "r2dtable"             "cpgram"              
## [235] "mcnemar.test"         "NLSstClosestX"        "makepredictcall"     
## [238] "NLSstLfAsymptote"     "simulate"             "toeplitz"            
## [241] "SSasympOrig"          "summary.manova"       "model.extract"       
## [244] "qhyper"               "model.tables"         "add1"                
## [247] "SSfol"                "SSasymp"              "ts.plot"             
## [250] "Gamma"                "plot.stepfun"         "termplot"            
## [253] "bartlett.test"        "oneway.test"          "step"                
## [256] "qlogis"               "df.kernel"            "quasi"               
## [259] "coef"                 "promax"               "factor.scope"        
## [262] "poisson"              "embed"                "dcauchy"             
## [265] "na.action"            "rect.hclust"          "SSfpl"               
## [268] "bw.bcv"               "as.hclust"            "varimax"             
## [271] "model.offset"         "df.residual"          "nextn"               
## [274] "hclust"               "smooth.spline"        "qtukey"              
## [277] "bw.nrd0"              "ppr"                  "power.prop.test"     
## [280] "pacf"                 "pwilcox"              "bw.nrd"              
## [283] "rsignrank"            "quantile"             "stl"                 
## [286] "AIC"                  "end"                  "sortedXyData"        
## [289] "lowess"               "lm.wfit"              "pf"                  
## [292] "princomp"             "terms"                "lm.influence"        
## [295] "model.frame"          "qwilcox"              "stat.anova"          
## [298] "qchisq"               "update.default"       "model.response"      
## [301] "drop.scope"           "residuals"            "median"              
## [304] "cycle"                "DF2formula"           "constrOptim"         
## [307] "pt"                   "deriv3"               "variable.names"      
## [310] "qf"                   "summary.aov"          "update"              
## [313] "rwilcox"              "pairwise.table"       "model.matrix.lm"     
## [316] "expand.model.frame"   "acf"                  "proj"                
## [319] "bw.SJ"                "numericDeriv"         "uniroot"             
## [322] "ARMAtoMA"             "ksmooth"              "qt"                  
## [325] "dffits"               ".checkMFClasses"      "rstudent"            
## [328] "rf"                   "plclust"              "manova"              
## [331] "dwilcox"              ".vcov.aliased"        "kernapply"           
## [334] ".MFclass"             "cutree"               "spec.ar"             
## [337] "cmdscale"             "poly"                 "dweibull"            
## [340] "optimise"             "formula"              "sd"                  
## [343] "rt"                   "loglin"               "qbinom"              
## [346] "median.default"       "gaussian"             "model.matrix"        
## [349] "fitted.values"        "var"                  "binomial"            
## [352] "arima.sim"            "logLik"               "selfStart"           
## [355] "reformulate"          "naresid"              "StructTS"            
## [358] "interaction.plot"     "SSlogis"              "terms.formula"       
## [361] "supsmu"               "dgamma"               "weighted.residuals"  
## [364] "smooth"               "kernel"               "confint"             
## [367] "mvfft"                "kruskal.test"         "spec.pgram"          
## [370] "glm"                  "ls.diag"              "pairwise.wilcox.test"
## [373] "NLSstRtAsymptote"     "pgamma"               "rpois"               
## [376] "arima"                "rgamma"               "t.test"              
## [379] "biplot"               "xtabs"                "ts"                  
## [382] "SSasympOff"           "is.empty.model"       "summary.lm"          
## [385] "dummy.coef.lm"        "binom.test"           "sigma"               
## [388] "prop.test"            "na.pass"              "make.link"           
## [391] "summary.stepfun"      "reshape"              "ftable"              
## [394] "density.default"      "dfbetas"              "contrasts"           
## [397] "psignrank"            "polym"                "model.frame.default" 
## [400] "rgeom"                "contr.treatment"      "qlnorm"              
## [403] "lm.fit"               "arima0"               "offset"              
## [406] "power.anova.test"     "loess"                "pairwise.prop.test"  
## [409] "kmeans"               "aggregate.ts"         "relevel"             
## [412] "spectrum"             "model.weights"        "rexp"                
## [415] ".lm.fit"              "printCoefmat"         "PP.test"             
## [418] "cov.wt"               "residuals.lm"         "replications"        
## [421] "fisher.test"          "qexp"                 "screeplot"           
## [424] "contr.helmert"        "deltat"               "medpolish"           
## [427] "pexp"                 "rWishart"             "ccf"                 
## [430] "time"                 "anova"                "IQR"                 
## [433] "KalmanLike"           "optimHess"            "pweibull"            
## [436] "p.adjust.methods"     "read.ftable"          "cancor"              
## [439] "fft"                  "qpois"                "tsdiag"              
## [442] "power"                "getInitial"           "SSgompertz"          
## [445] "bandwidth.kernel"     "quade.test"           "mauchly.test"        
## [448] "approx"               ".preformat.ts"        "deriv"               
## [451] "spec.taper"           "ecdf"                 "dhyper"              
## [454] "dpois"                "setNames"             "dlogis"

search() to see loaded libraries in the environment.

search()
## [1] ".GlobalEnv"        "package:stats"     "package:graphics" 
## [4] "package:grDevices" "package:utils"     "package:datasets" 
## [7] "package:methods"   "Autoloads"         "package:base"

Early waning systems

Always use TRUE and FALSE over T and F

Message function

  • Signals to the user the state of a process
  • This isn’t an error - it’s just helpful information
simulate <- function() rnorm(1)
N <- 10
results <- numeric(N)
for(i in 1:N) {
  results[i] <- simulate()
  # Show a progress report
  message("Simulation ", i, " complete")
}
## Simulation 1 complete
## Simulation 2 complete
## Simulation 3 complete
## Simulation 4 complete
## Simulation 5 complete
## Simulation 6 complete
## Simulation 7 complete
## Simulation 8 complete
## Simulation 9 complete
## Simulation 10 complete

warning and Stop functions

  • Warnings indicate something may have gone wrong in the code, but you can still proceed.

  • Using stop() indicates something has gone wrong in the code and so code execution stops.

# Stop the execution if ages are negative
mean_age <- function(ages) {
   if(any(ages < 0)) {
    stop("You have negative ages!")
   } else if(any(ages > 150)){
    warning("Probably no one has more than 150 years")
  }
  
  m <- mean(ages)
  return(m)
}
  • Avoid . in variable names because ir leads to confusion with S3 objects

Linter package

Structure of R projects

Project set-up

  • Has its own directory
  • has a sensible name

The directory name gives the context of the scrips

  1. input/ folder:
  • csv and excel files
  • no R code
  1. R/
  • load.R: Loads the data from input/
  • clean.R: for cleaning the data
  • function.R any helper functions
  • analysis The actual analysis
  1. output/ for output generated data
  2. graphics/ generated plots

The R/ directory create the contents of output/ and graphics/