数据-R语言-图表-决策-Linux-PythonR相关知识

R语言基础--包的操作与内置数据集

2019-07-30  本文已影响0人  天涯清水

R语言包的安装

参考文章

在R中大概有几种包的安装方式。

install.packages()常规包的安装

括号里面包的名称要加英文引号,在列出的CRAN镜像站点列表中选择一个进行下载,例如

install.packages(“ggplot2”)

安装包的时候可以切换安装源,如下所示:

install.packages(pkgs, lib, repos = getOption("repos"),
    contriburl = contrib.url(repos, type),
    method, available = NULL, destdir = NULL,
    dependencies = NA, type = getOption("pkgType"),
    configure.args = getOption("configure.args"),
    configure.vars = getOption("configure.vars"),
    clean = FALSE, Ncpus = getOption("Ncpus", 1L),
    verbose = getOption("verbose"),
    libs_only = FALSE, INSTALL_opts, quiet = FALSE,
    keep_outputs = FALSE, ...)

使用格式为:

install.packages("ABC",repos="http://mirror.bjtu.edu.cn/ ")

使用devtools从Github上安装包

如果是要从GitHub上安装包,需要先安装devtools,如下所示:

install.packages("devtools")
install_github("genomicsclass/dagdata")

其它的包安装命令,如下所示:

install.packages("installr")   # 下载并安装 installr 包
library(installr)              # 装载 installr 包
install.RStudio()              # 下载并安装 RStudio IDE
install.Rtools()               # 你需要 Rtools 来构建自己的包
install.git()                  #git 提供了代码的版本控制功能

如果要想把R包安装到其他位置,可以使用以下代码:

install.packages( 
  c("xts", "zoo"),
  lib = "some/other/folder/to/install/to", 
  repos = "http://www.stats.bris.ac.uk/R/")

其中lib参数就是安装的包的位置,repos就是安装源。

通过BiocLite来安装生信工具

生信很多工具是在bioconductor上,因此需要biocLite,由于R版本升级,现在安装都是BiocManager::install()
此处仍然列出,如下所示:

#source("https://bioconductor.org/biocLite.R")
#options(BioC_mirror="http://mirrors.ustc.edu.cn/bioc/")
# 使用相应的镜像

#biocLite(c("ALL","CLL", "pasilla", "airway")) #数据包
#biocLite(c("limma","DESeq2", "clusterProfiler")) #软件包

通过BiocManager来安装生信工具

在使用bioconductor时由于需要在线连接才能安装包,现在很多已经使用BiocManager的方式来安装,安装代码如下所示:

if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("ballgown", version = "3.8")

批量下载并且加载R包

list.of.packages <- c("xx", "yy") # replace xx and yy with package names
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
lapply(new.packages, require, character.only=T)

使用if语句安装并加载包

通过if语句,可以判断某个包是否存在,如果不存在,就先下载,后加载,如下所示:

#另外可以检测某个包是否存在,只有不存在时才会安装
if (! require ('reshape2')){
    install.package("reshape2")
    library(reshape2)
}

如果是bioconductor上的包,也可以按以下方式进行安装:

if (! require ('CLL')){
    options(BioC_mirror="http://mirrors.ustc.edu.cn/bioc/")
    BiocInstaller::biocLite('CLL',ask = F, suppressUpdates = T)
}

包的加载

包的载入函数为library()require(),安装完包后,需要加载才能使用其中的函数,此时括号中不使用引号。两者的不同之处在于library()载入之后不返回任何信息,而require()载入后则会返回TRUE,因此require()适合用于程序的书写。

library(ggplot2)

require(foreign)

Loading required package: foreign

如果想不加载包就使用其中的函数,则需要使用双冒号,即::,看一个案例:

x <- rnorm(1000)
skewness(x)

运行结果如下所示:

skewness(x)
Error in skewness(x) : could not find function "skewness"

结果显示,没有skewness这个函数,因为这个函数是moments包中的函数,没有加载这个包,就无法使用这个函数。现在我们在没有加载这个包的情况下,使用双冒号来看一下:

moments::skewness(x) 

[1] -0.01674

再用library()来使用一下:

library(moments)
skewness(x)

[1] -0.01674

使用双冒号这种方式在一种情况下比较适合。

这种情况就是:假设我们同时加载了A包与B包,A包中有一个名为a()的函数,B包中也有一个名为a()的函数。此时,如果先导入A包,再导入B包,B包中的a()函数就会屏蔽A包中的a()函数,也就是说,这两个同名函数就会出现冲突。

因此为了避免出现这种情况,可以不加载A包,也不加载B包,而是将它们的同名函数提取出来,如下所示:

fun1 <- A::a

fun2 <- B::a

如果你此时已经恰好载入一个包,想要解决绑定,就可以使用unloadNamespace()函数即可,例如:

unloadNamespace("moments")

查看一个包的帮助

help(package="base")

卸载包

detach(),这是library()的反向操作,此操作主要是为了避免某些包中的函数名称相同,造成冲突,注意与library()的参数不同,detach()参数为detach(package:包的名称),library(包的名称),例如:

library(ggplot2) #加载包
(.packages()) #列出当前已经加载的包

 [1] "foreign"   "ggplot2"   "stats"     "graphics"  "grDevices" "utils"    

 [7] "datasets"  "methods"   "base"

detach(package:ggplot2)  #卸载ggplot2包

(.packages()) #列出当前已经加载的包

 [1] "foreign"   "stats"     "graphics"  "grDevices" "utils"     "datasets" 

 [7] "methods"   "base"

删除包remove.packages()

使用条件:R语言自带的install.packages()函数来安装一个包时,都是默认安装最新版的。 但是有些R包的开发者他会引用其它的一些R包,但是它用的是旧版本的功能,自己来不及更新或者疏忽了。 而我们又不得不用他的包,这时候就不得不卸载最新版包,转而安装旧版本包。

查询加载的包

search()

search()

 [1] ".GlobalEnv"        "package:stats"     "package:graphics" 

 [4] "package:grDevices" "package:utils"     "package:datasets" 

 [7] "package:methods"   "Autoloads"         "package:base"

.libPaths()能够显示库所在的位置

.libPaths()

 [1] "C:/Users/Cloud/Documents/R/win-library/3.1"

 [2] "C:/Program Files/R/R-3.1.3/library"

library()显示库中有哪些包

library()
backports               Reimplementations of Functions Introduced Since
                        R-3.0.0
base64enc               Tools for base64 encoding
bitops                  Bitwise Operations
bookdown                Authoring Books and Technical Documents with R
                        Markdown
caTools                 Tools: moving window statistics, GIF, Base64,
                        ROC AUC, etc.
cellranger              Translate Spreadsheet Cell Ranges to Rows and
                        Columns
digest                  Create Compact Hash Digests of R Objects
evaluate                Parsing and Evaluation Tools that Provide More
                        Details than the Default

查看已经安装的包

函数installed.packages()

如下所示:

image

还可以这么输入代码:

pkgs <- installed.packages()

colnames(pkgs)

结果如下所示:

pkgs <- installed.packages()

colnames(pkgs)

 [1] "Package"               "LibPath"               "Version"              

 [4] "Priority"              "Depends"               "Imports"              

 [7] "LinkingTo"             "Suggests"              "Enhances"             

[10] "License"               "License_is_FOSS"       "License_restricts_use"

[13] "OS_type"               "MD5sum"                "NeedsCompilation"     

[16] "Built"

当需要检查包是否已经安装时,可以使用以下代码:

c("moments", "Built") %in% installed.packages()[, "Package"]

结果如下所示:

c("moments", "Built") %in% installed.packages()[, "Package"]

[1]  TRUE FALSE

查看包的版本

查看包的版本可以通过下面代码实现:


[1] "3.2.0"

包的更新update.packages()

update.packages()

查看本地的包

查看默认加载的包,忽略基本的包

getOption("defaultPackages")

[1] "datasets"  "utils"     "grDevices" "graphics"  "stats"     "methods"

查看当前已经加载过的包

(.packages())

[1] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"
[7] "base"

显示所有可用的包

(.packages(all.available=TRUE))

(.packages(all.available=TRUE))

  [1] "bitops"       "car"          "caTools"      "coin"        
  [5] "colorspace"   "crayon"       "curl"         "dichromat"   
  [9] "digest"       "evaluate"     "formatR"      "fun"         
 [13] "ggplot2"      "gtable"       "highr"        "htmltools"   
 [17] "httr"         "ISwR"         "jsonlite"     "KMsurv"      
 [21] "knitr"        "labeling"     "lme4"         "magrittr"    
 [25] "maps"         "maptools"     "markdown"     "MatrixModels"
 [29] "memoise"      "mime"         "minqa"        "mnormt"      
 [33] "modeltools"   "multcomp"     "munsell"      "mvtnorm"     
 [37] "nloptr"       "openssl"      "pbkrtest"     "plyr"        
 [41] "praise"       "psych"        "quantreg"     "R6"          
 [45] "RColorBrewer" "Rcpp"         "RcppEigen"    "RCurl"       
 [49] "reshape2"     "rmarkdown"    "sandwich"     "scales"      
 [53] "sp"           "SparseM"      "stringi"      "stringr"     
 [57] "swirl"        "testthat"     "TH.data"      "yaml"        
 [61] "zoo"          "base"         "boot"         "class"       
 [65] "cluster"      "codetools"    "compiler"     "datasets"    
 [69] "foreign"      "graphics"     "grDevices"    "grid"        
 [73] "KernSmooth"   "lattice"      "MASS"         "Matrix"      
 [77] "methods"      "mgcv"         "nlme"         "nnet"        
 [81] "parallel"     "rpart"        "spatial"      "splines"     
 [85] "stats"        "stats4"       "survival"     "tcltk"       
 [89] "tools"        "utils"

自定义启动时候的加载包

如果需要长期使用某个包的话,每次开启都需要输入library(),比较麻烦,因此可以让R启动时自动加载某些包。在R的安装目录/etc/Rprofile.site加入下载语句:

例如让R启动时自动加载ggplot2包

local({old <- getOption(“defaultPackages”)
options(defaultPackages = c(old, “ggplot2”))})

安装包,并加载包

if(!require("multcomp")){

  install.packages("multcomp")

  library(multcomp)

}

常用R包的搜集

数据导入

以下R包主要用于数据导入和保存数据

  • feather:一种快速,轻量级的文件格式。在R和python上都可使用
  • readr:实现表格数据的快速导入。中文介绍可参考这里
  • readxl:读取Microsoft Excel电子表格数据
  • openxlsx:读取Microsoft Excel电子表格数据
  • googlesheets:读取google电子表格数据
  • haven:读取SAS,SPSS和Stata统计软件格式的数据
  • httr:从网站开放的API中读取数据
  • rvest:网页数据抓取包
  • xml2:读取HTML和XML格式数据
  • webreadr:读取常见的Web日志格式数据
  • DBI:数据库管理系统通用接口包
  • RMySQL:用于连接MySQL数据库的R包
  • RPostgres:用于连接PostgreSQL数据库的R包
  • bigrquery用于连接Google BigQuery的R包
  • PivotalR:用于读取Pivitol(Greenplum)和HAWQ数据库中的数据
  • dplyr:提供了一个访问常见数据库的接口
  • data.table:data.table包的fread()函数可以快速读取大数据集
  • git2r:用于访问git仓库

数据整理

以下R包主要用于数据整理,以便于你后续建模分析:

  • tidyr:用于整理表格数据的布局
  • dplyr:用于将多个数据表连接成一个整齐的数据集
  • purrr:函数式编程工具,在做数据整理时非常有用。
  • broom:用于将统计模型的结果整理成数据框形式
  • zoo:定义了一个名zoo的S3类型对象,用于描述规则的和不规则的有序的时间序列数据。

数据可视化

以下R包用于数据可视化:

数据转换

以下R包用于将数据转换为新的数据类型

统计建模与推断

下述R包是统计建模最常用的几个R包,其中的一些R包适用于多个主题。

沟通交流

以下R包用于实现数据科学结果的自动化报告,以便于你跟人们进行沟通交流。

自动化分析

以下R包用于创建自动化分析结果的数据科学产品:

程序开发

以下这些包主要用于开发自定义的R包:


实验数据

以下R包给出了案例实战过程中可用的训练数据集:

查看R的版本

sessionInfo() # 要加括号

如下所示:

 sessionInfo() # 要加括号

R version 3.4.0 (2017-04-21)

Platform: x86_64-w64-mingw32/x64 (64-bit)

Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:

[1] LC_COLLATE=Chinese (Simplified)_China.936  LC_CTYPE=Chinese (Simplified)_China.936   

[3] LC_MONETARY=Chinese (Simplified)_China.936 LC_NUMERIC=C                              

[5] LC_TIME=Chinese (Simplified)_China.936    

attached base packages:

[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:

[1] downloader_0.4 rafalib_1.0.0 

loaded via a namespace (and not attached):

[1] compiler_3.4.0     tools_3.4.0        RColorBrewer_1.1-2 digest_0.6.15

查看R语言的内置数据集data()

R的基本包中有一个叫datasets,里面全是示例数据集,供用户练习用。同时也可以使用data()来查看所有已经成功加载的包的数据集:

Data sets in package ‘datasets’:

AirPassengers                         Monthly Airline Passenger Numbers 1949-1960

BJsales                               Sales Data with Leading Indicator

BJsales.lead (BJsales)                Sales Data with Leading Indicator

...

略

如果需要查看更完整的列表,包括已安装的所有包的数据,可以使用下面代码:

data(package = .packages(TRUE))

加载特定包中的数据集

如果想要访问任意数据集里面的数据,可以使用data()函数,传入数据集的名称以及所在的包名(如果这个包已经被加载了,就可以不用packages="包名"这个以参数了),如下所示:

data("kidney", package = "survival")
head(kidney)

这个命令是调用survival这个包中的kidney这个数据集,如下所示:

data("kidney", package = "survival")
head(kidney)
  id time status age sex disease frail
1  1    8      1  28   1   Other   2.3
2  1   16      1  28   1   Other   2.3
3  2   23      1  48   2      GN   1.9
4  2   13      0  48   2      GN   1.9
5  3   22      1  32   1   Other   1.2
6  3   28      1  32   1   Other   1.2

参考资料

  1. http://www.xueqing.tv/cms/article/198
  2. http://blog.fens.me/
  3. 学习R.[美] Richard,Cotton 著刘军 译
  4. R 从安装开始:BiocLite 到 BiocManager
  5. R语言编程指南.任坤 著,王婷,赵孟韬,王泽贤 译
上一篇 下一篇

猜你喜欢

热点阅读