0
0
R-programmingHow-ToBeginner · 3 min read

How to Install R Packages from R Console Easily

To install a package in R, use the install.packages() function with the package name as a string. For example, install.packages("ggplot2") installs the ggplot2 package from CRAN.
📐

Syntax

The basic syntax to install a package in R is:

  • install.packages("package_name"): Installs the package named package_name from CRAN.
  • dependencies = TRUE: Optional argument to also install packages that the main package depends on.
  • repos: Optional argument to specify the repository URL if you want to use a mirror other than the default.
r
install.packages("package_name", dependencies = TRUE, repos = "https://cran.r-project.org")
💻

Example

This example shows how to install the popular ggplot2 package for creating graphs in R.

r
install.packages("ggplot2")
Output
Installing package into ‘/your/library/path’ (as ‘lib’ is unspecified) trying URL 'https://cran.r-project.org/src/contrib/ggplot2_3.4.2.tar.gz' Content type 'application/x-gzip' length 3260000 bytes (3.1 MB) ================================================== downloaded 3.1 MB * installing *source* package ‘ggplot2’ ... ** package ‘ggplot2’ successfully unpacked and MD5 sums checked ** using staged installation ** R ** data ** byte-compile and prepare package for lazy loading ** help ** building package indices ** testing if installed package can be loaded ** DONE (ggplot2) The downloaded source packages are in ‘/tmp/RtmpXXXXXX/downloaded_packages’
⚠️

Common Pitfalls

Common mistakes when installing packages in R include:

  • Forgetting to put the package name in quotes, e.g., install.packages(ggplot2) instead of install.packages("ggplot2").
  • Not having an internet connection or firewall blocking access to CRAN.
  • Trying to install packages without write permission to the library folder.
  • Not specifying the repository if the default is unavailable.

Always check for error messages and ensure your R session has permission to install packages.

r
## Wrong way (missing quotes)
install.packages(ggplot2)

## Right way
install.packages("ggplot2")
Output
Error in install.packages(ggplot2) : object 'ggplot2' not found
📊

Quick Reference

FunctionDescription
install.packages("pkg")Install package named 'pkg' from CRAN
library(pkg)Load installed package 'pkg' into R session
update.packages()Update all installed packages to latest versions
remove.packages("pkg")Remove package 'pkg' from your library

Key Takeaways

Use install.packages("package_name") with quotes to install packages in R.
Ensure you have internet access and write permission to install packages.
Check error messages carefully to fix common installation issues.
Use library("package_name") to load installed packages for use.
Specify repos argument if you want to use a specific CRAN mirror.