Packages in R Programming: An Introduction

The post is an introduction tutorial about Packages in R Programming. In R language functions and datasets are all stored in packages. The content of a package is only available when a package is loaded using the library() function.

To see which R packages are installed, write the following command (without argument)

library( )

To load a particular installed package, use the package name as the argument to the library() function, that is,

library(MASS)

Installing and Updating Packages in R Programming

If the computer system is connected to the internet and a required package is not installed on one’s computer, the user can use the install.packages() function to install the required package. To update the already installed package one can use the update.package() function. The search() function can be used to see which packages are loaded into computer memory.

Classification of R Packages

R packages can be classified as standard (base) packages and contributed packages. The standard (or base) packages are considered part of the R source code. The base packages contain the basic functions that allow R to work. The base packages also contain datasets and standard statistical and graphical functions. The standard R functions are automatically available in any R installation, that is, you do not need to install them.

The standard R packages are written by authors. These packages implement some specialized statistical methods, and access to datasets and hardware. The contributed packages are distributed with every binary distribution of R and are available for download from CRAN and other repositories such as Bioconductor.

Frequently Asked Questions About R: Packages in R Programming

R Namespace

R packages can have a namespace. Namespaces (i) allow the package writer to hide functions and data that are meant only for internal use, (ii) prevent functions from breaking when a user picks a name that clashes with one in the packages, and (iii) provide a way to refer to an object within a particular package.

For example, in R the t() function is the transpose function. A user can define his own t() function. The namespaces will prevent the user’s definition from taking procedure and breaking every function that tries to transpose the matrix.

Two operators work with namespaces, (i) :: double colon operator and triple colon operator :::. The double colon operator selects definitions from a particular namespace. For example, the t() function is available as the base::t, because it is defined in the base package. The function that is exported from the package can be retrieved with a double colon operator.

The tiple colon operator acts as a double colon operator but it also allows access to hidden objects. The getAnywhere() function can be used to search for multiple packages.

Note: Packages are interdependent, and loading one package may cause other packages to be automatically loaded. The colon operators also cause automatic loading of the associated package. the package is not added to the search list when a package with namespaces is loaded automatically.

FAQs about R Packages

  1. What is an R package?
  2. How an R package can be loaded in a session?
  3. What is the use of getAnywhere() function in R?
  4. What is the use of the colon operator for package loading
  5. What is namespace in R language?
  6. Who writes or develops R packages?
Available R Packeges in Local and Global Directory

SPSS Data Analysis

MCQs General Knowledge

Namespaces in R Language Made Easy

The packages can have namespaces in R Language, and currently, all of the base and recommended packages do except the dataset packages. Understanding the use of namespaces is vital if one plans to submit a package to CRAN because CRAN requires that the package plays nicely with other submitted packages on CRAN.

Namespaces in R Language

Namespaces in R Language are essential tools for organizing code and preventing naming conflicts.
They become especially important when dealing with multiple packages, each potentially containing functions or objects with the same names.

Namespaces in R Language ensure that other packages will not interfere with your code and that the package works regardless of the environment in which it’s run. In R Language, the namespace environment is the internal interface of the package. It includes all objects in the package, both exported and non-exported to ensure that every function can find every other function in the package.

For example, plyr and Hmisc both provide a function namely summarize(). Loading plyr package and then Hmise, the summarize() function will refer to the Hmisc. However, loading the package in the opposite order, the summarize() function will refer to the plyr package version.

To avoid confusion, one can explicitly refer to the specific function, for example,

Hmisc::summarize

and

plyr::summarize
Namespaces in R Language

Now, the order in which the packages are loaded would not matter.

The Namespaces in R Language do three things:

  • Namespaces allow the package writer to hide functions and data that are meant only for internal use,
  • Namespaces prevent functions from breaking when a user (or other package writers) picks a name that clashes with one in the package, and
  • Namespaces in R provide a way to refer to an object within a particular package

Namespace Operators

In R language, two operators work with namespaces.

  • Doule-Colon Operator
    The double-colon operator:: selects definitions from a particular namespace. The transpose function t() will always be available as the base::t because it is defined in the base package. Only functions exported from the package can be retrieved this way.
  • Triple-Colon Operator
    The triple-colon operator ::: acts like the double-colon operator but also allows access to hidden objects. Users are more likely to use the getAnywhere() function, which searches multiple packages.

Packages are often interdependent, and loading one may cause others to be automatically loaded. The colon operators will also cause automatic loading of the associated package. When packages with namespaces are loaded automatically they are not added to the search list.

Benefits of using namespaces:

  • Clarity: Namespaces clarify the code by avoiding ambiguity when using common function names across different packages.
  • Fewer conflicts: Namespaces prevent errors that might arise if a user accidentally overwrites an object from another package with the same name.
  • Modular design: Namespaces promotes a modular approach to code organization, making managing and reusing code across projects easier.

FAQs about Namespaces in R Language

  1. What is namespace in R Language?
  2. What do namespaces in R language ensure?
  3. List and discuss namespace operators.
  4. Write a note on the benefits of using namespaces in R Language.
  5. What is the purpose of getAnywhere() function in R?
  6. Discuss double colon and triple colon operators.

R Language Basics: Frequently Asked Questions

Online MCQs Test Preparation Website with Answers

mctest R Package for Detection of Collinearity

In this post, I will discuss the existence and detection of collinearity among regressors using the mctest R Package.

The problem of multicollinearity plagues the numerical stability of regression estimates. It also causes some serious problems in the validation and interpretation of the regression model. Consider the usual multiple linear regression model,

$$y = X \beta+u$$

where $y$ is an $n\times 1$ vector of observation on dependent variable, $X$ is known design matrix of order $\times p$, having full-column rank $p$, $\beta$ is $p \times 1$ vector of unknown parameters and $u$ is an $n\times 1$ vector of random errors with mean zero and variance $\sigma^2 I_n$, where $I_n$ is an identity matrix of order $n$.

Collinearity Among Regressors

The existence of linear dependence (relationship) between regressors can affect the regression model’s ability to estimate the model’s parameters. Therefore, multicollinearity is a lack of independence or the presence of interdependence signified by usually high inter-correlations within a set of regressors (predictors).

In case of severe multicollinearity (mathematically when the matrix is ill-conditioned) the $X’X$ matrix cannot be inverted, implausible signs of coefficients, low t-ratios, high R-squared values, inflated standard errors, wider confidence intervals, very large condition number (CN) and non-significant and/or magnitude of regression coefficient estimates are some of the possible issues.

There are many diagnostic methods are available to check the existence of collinearity among regressors, such as variance inflation Factor (VIF), values of pair-wise correlation among regressors, eigenvalues, CN, Farrar and Glauber tests, Theil’s measure, and Klein’s rule, etc.

Our recently developed R package mctest computes several collinearity diagnostics measures to test the existence of collinearity among regressors. We classified these measures as individual collinearity diagnostics and overall collinearity diagnostics. Overall collinearity diagnostic includes determinant of $X’X$ matrix, red indicator, Farrar Chi-Square test, Theil indicator, CN, and the sum of lambda inverse values. Individual collinearity diagnostics include VIF/ TOL, Farrar and Glauber Wi test, the relationship between $R^2$ and F-test, corrected VIF (CVIF), and Klein’s rule.

How to use the mctest R Package

You must have installed and loaded the mctest R Package to start with the testing/ detection of collinearity among regressors. As an example, we used Hald data which is already bundled in the mctest R Package.

mctest R package have 4 functions namely, mctest(), omcdiag(), imcdiag() and mc.plot() functions. The mctest() function can be used to have overall and/or individual collinearity diagnostic. The mc.plot() is used to draw the graph of VIF and eigenvalues to judge collinearity among regressors.

mctest illustrative Example

Arguments of mctest with syntax are

mctest(x, y, type = c("o", "I", "b"), na.rm = TRUE, Inter = TRUE, method = NULL, corr = FALSE, detr = 0.01, red = 0.5, theil = 0.5, cn = 30, vif = 10, tol = 0.1, conf = 0.95, cvif = 10, leamer = 0.1, all = all)

See the detail of each argument and see the mctest package documentation. Following are a few commands that can be used to get different collinearity diagnostics.

x <- Hald[ ,-1]     # X variables from Hald data
> y <- Hald[ ,1]      # y variable from Hald data

mctest(x, y)        # default collinearity diagnostics
mctest(x, y, type = "i")  # individual collinearity diagnostics
mctest(x, y, type = "o") # overall collinearity diagnostics

Overall Collinearity Diagnostics in R

For overall collinearity diagnostics, eigenvalues, and condition numbers are also produced whether the intercept term is included or not. The syntax of omcdiag() function is

omcdiag(x, y, na.rm = TRUE, Inter = True, detr = 0.01, red = 0.5, conf = 0.95, theil = 0.5, cn = 30, …)

Determinant of the correlation matrix, Farrar test of Chi-square, Red indicator, the sum of lambda inverse values, Theils’ indicator, and CN.

omcdiag(x, y, Inter=FALSE)
omcdiag(x, y)[1]

omcidag(x,y, detr = 0.001, conf = 0.99)

For the last command (with the threshold for determinant and confidence interval for the Farrar and Glauber test). The output is,

mctest r package overall collinearity diagnostics

Individual Collinearity Diagnostics in R

The general syntax of individual collinearity Diagnostics in R Language through mctest packages is:

imcdiag(x, y, method = NULL, na.rm = TRUE, corr = FALSE, vif = 10, tol = 0.1, conf = 0.95, cvif = 10, leamer = 0.1, all = all)

Function imcdiag() detects the existence of multicollinearity due to certain X-variable. This includes VIF, TOL, Klein’s rule, CVIF, F&G test of Chi-square and F-test.

imcdiag(x = x, y)
imcdiag(x = x, y, corr = TRUE) # correlation matrix
imcdiag(x = x, y, vif = 5, leamer = 0.05)  # with threshold of VIF and leamer method
mctest r package individual collinearity diagnostics
imcdiag(x = x, y, all = True)
imcdiag(x = x, y, all = TRUE, vif = 5, leamer = 0.2, cvif = 5)
mctest: individual collinearity diagnostics

Graphical Representation of VIF and Eigenvalues

mc.plot(x, y, Inter = FALSE, vif = 10, ev = 0.01)
mc.plot(x, y)
mc.plot(x, y, vif = 5, ev = 0.2)
mctest: collinearity diagnostic measures

For further details about collinearity diagnostic see