R install.packages() Function - Installing Packages

R 语言实例R Language Examples

The R install.packages() function is used to install R packages from CRAN or other mirror sources.

There are over 20,000 packages in the R ecosystem, and packages are the core of R's powerful functionality.

The syntax of the install.packages() function is as follows:

install.packages(pkgs, repos = getOption("repos"),
                 dependencies = NA)

Parameter description:

  • pkgsThe package name to install (character vector).

  • reposCRAN mirror source address.

  • dependenciesWhether to install dependency packages. TRUE means install all dependencies.

Example

# Installation of common packages (example, actually downloads from network)
# install.packages("ggplot2") # Install a single package
# install.packages(c("dplyr", "tidyr")) # Install multiple packages

# View currently installed packages
installed <- installed.packages()
print("First 5 installed packages:")
print(head(installed[, c("Package", "Version")], 5))

# View CRAN mirror
print("Current CRAN mirror:")
print(getOption("repos"))

# Set mirror (Tsinghua source recommended for Chinese users)
# options(repos = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))

Executing the above code outputs:

[1] "已安装包的前 5 个:"
     Package    Version
base "base"     "4.3.0"
boot "boot"     "1.3-28"
...
[1] "当前 CRAN 镜像:"
                                CRAN
"https://cran.rstudio.com/"

When using R to install packages in China, it is recommended to set the Tsinghua or USTC CRAN mirror to speed up downloads.

R 语言实例R Language Examples

Other Extensions