R包是R函数的集合,包含代码和样本数据.它们存储在R环境中名为"library"的目录下.默认情况下,R在安装期间安装一组软件包.如果出于某些特定目的需要更多包,则会在以后添加.当我们启动R控制台时,默认情况下只有默认包可用.已经安装的其他软件包必须显式加载以供将要使用它们的R程序使用.
R语言中提供的所有软件包都列在 R Packages.
以下是要执行的命令列表用于检查,验证和使用R包.
检查可用的R包
获取包含R包的库位置
.libPaths()
当我们执行上述操作时代码,它产生以下结果.它可能会因您的电脑的本地设置而异.
[2]"C:/Program Files/R/R-3.2.2/library"
获取所有已安装软件包的列表
library()
当我们执行上面的代码时,它会产生以下结果.它可能会因您的电脑的本地设置而异.
Packages in library ‘C:/Program Files/R/R-3.2.2/library’:base The R Base Packageboot Bootstrap Functions (Originally by Angelo Canty for S)class Functions for Classificationcluster "Finding Groups in Data": Cluster Analysis Extended Rousseeuw et al.codetools Code Analysis Tools for Rcompiler The R Compiler Packagedatasets The R Datasets Packageforeign Read Data Stored by 'Minitab', 'S', 'SAS', 'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ...graphics The R Graphics PackagegrDevices The R Graphics Devices and Support for Colours and Fontsgrid The Grid Graphics PackageKernSmooth Functions for Kernel Smoothing Supporting Wand & Jones (1995)lattice Trellis Graphics for RMASS Support Functions and Datasets for Venables and Ripley's MASSMatrix Sparse and Dense Matrix Classes and Methodsmethods Formal Methods and Classesmgcv Mixed GAM Computation Vehicle with GCV/AIC/REML Smoothness Estimationnlme Linear and Nonlinear Mixed Effects Modelsnnet Feed-Forward Neural Networks and Multinomial Log-Linear Modelsparallel Support for Parallel computation in Rrpart Recursive Partitioning and Regression Treesspatial Functions for Kriging and Point Pattern Analysissplines Regression Spline Functions and Classesstats The R Stats Packagestats4 Statistical Functions using S4 Classessurvival Survival Analysistcltk Tcl/Tk Interfacetools Tools for Package Developmentutils The R Utils Package
获取当前加载的所有包R环境
search()
当我们执行上面的代码时,它会产生以下结果.它可能会因您的电脑的本地设置而异.
[1] ".GlobalEnv" "package:stats" "package:graphics" [4] "package:grDevices" "package:utils" "package:datasets" [7] "package:methods" "Autoloads" "package:base"
安装新软件包
有两种方法可以添加新的R包.一种是直接从CRAN目录安装,另一种是将软件包下载到本地系统并手动安装.
直接从CRAN安装
以下命令直接从CRAN网页获取包,并在R环境中安装包.系统可能会提示您选择最近的镜像.选择适合您所在位置的那个.
install.packages("Package Name") # Install the package named "XML". install.packages("XML")
手动安装包
转到链接 R Packages 下载所需的软件包.将程序包保存为本地系统中适当位置的 .zip 文件.
现在可以运行以下命令在R环境中安装此程序包.
install.packages(file_name_with_path, repos = NULL, type = "source")# Install the package named "XML"install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")
将包加载到库
在可以在代码中使用包之前,必须将它加载到当前的R环境中.您还需要加载先前已安装但在当前环境中不可用的软件包.
使用以下命令加载软件包 :
library("package Name", lib.loc = "path to library")# Load the package named "XML"install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")