Cook R数据科学与R语言R

暗藏玄机的Rprofile及R项目个性化定制

2019-07-04  本文已影响2人  Angeladaddy

相信大家在R脚本中都写过以下代码:

.libPaths()    #查看现在的R包安装路径
.libPaths("C:/Program Files/R/R-3.5.2/library")    
install.packages("packageName",lib="paths")    

以及

# bioconductor
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
# CRAN
options(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")

第一段脚本是指定包的安装路径,第二段是指定安装源的国内镜像。每个文件这样指定是比较麻烦的。其实这些都不用特殊指定,只需要通过编辑RProject

R的启动流程

每次R启动一个新的session:

  1. 读取R安装位置的Rprofile.site文件,如果是Linux通过apt安装的R ,此位置在/usr/lib/R/etc/Rprofile.site
  2. 读取home下的.Rprofile文件,~/.Profile
  3. 读取目录下的.Rprofile文件
    由此可见,全局设置可以写在/usr/lib/R/etc/Rprofile.site中,比如镜像设置;以下是这个文件原始的样子:
##                                              Emacs please make this -*- R -*-
## empty Rprofile.site for R on Debian
##
## Copyright (C) 2008 - 2018  Dirk Eddelbuettel and GPL'ed
##
## see help(Startup) for documentation on ~/.Rprofile and Rprofile.site

# ## Example of .Rprofile
# options(width=65, digits=5)
# options(show.signif.stars=FALSE)
# setHook(packageEvent("grDevices", "onLoad"),
#         function(...) grDevices::ps.options(horizontal=FALSE))
# set.seed(1234)
# .First <- function() cat("\n   Welcome to R!\n\n")
# .Last <- function()  cat("\n   Goodbye!\n\n")

# ## Example of Rprofile.site
# local({
#  # add MASS to the default packages, set a CRAN mirror
#  old <- getOption("defaultPackages"); r <- getOption("repos")
#  r["CRAN"] <- "http://my.local.cran"
#  options(defaultPackages = c(old, "MASS"), repos = r)
#})

## We set the cloud mirror, which is 'network-close' to everybody, as default
local({
    r <- getOption("repos")
    r["CRAN"] <- "https://cloud.r-project.org"
    options(repos = r)
})

以下为修改镜像后的

local({
    r <- getOption("repos")
    r["CRAN"] <- "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"
    r["BioC_mirror"] <- "https://mirrors.ustc.edu.cn/bioc/"
    options(repos = r)
})

而对于各个工程来说,我们就可以指定用到的R包的具体位置,这个就可以写在工程根目录下的Pprofile文件中。
额外插播一句,R的包安装策略是一个版本的包一个位置:比如我的:

> ls ~/R/x86_64-pc-linux-gnu-library/
3.4  3.6

那么,比如我现在想在我的新工程中使用伯克利大学的CRAN镜像(为何要是用这个镜像见之前的文章),我需要对我工程下的.Rprofile文件做如下编辑

options(repos = c(CRAN = "http://cran.cnr.berkeley.edu"))
.libPaths("~/R/win-library/mybiolib")
message("Using library: ", .libPaths()[1])

可以看到,我同时指定了CRAN镜像(此镜像将和R目录下的tuna镜像叠加使用)和我要使用的R包路径。这样做的好处就是我对每个工程进行了特殊定制。对R包进行了隔离。

最后注意设置全局RprofileRprofile.site时一定要小心,千万不要加入一些特殊内容,比如stringsAsFactors = TRUE 之类的,否则别人用你的脚本时可能连出错都不知道为什么。

上一篇下一篇

猜你喜欢

热点阅读