参考:https://www.jianshu.com/p/52da99126db4

前言

事情的起因是师兄群里的一张图:

01. 自定义R 的启动环境 - 图1

而我的R 呢?

01. 自定义R 的启动环境 - 图2

真无情呀。

这里尝试修改一下。

编辑文件

我们可以通过编辑.Rprofile 文件进行配置。类似linux 中的配置文件,R的配置文件编辑后,也会在启动R 时生效。

这里我们修改家目录下的.Rprofile 文件:

  1. file.edit(file.path("~", ".Rprofile"))

如果之前没有配置过,会创建一个新的文件。

01. 自定义R 的启动环境 - 图3

这里直接提供一下我的配置:

# start with welcome
.First <- function(){
  message("Hello Peng!")
  message(paste0("Welcome at ", date()))
  # 配置install 命令使用的线程
  n <- parallel::detectCores()
  options(Ncpus = n-1)
  n2 <- getOption("Ncpus", 1L)
  message(paste0("We will use ", n2, " cores for installing.\n"))
}


# finish with goodbye
.Last <- function(){
  cat("\n Goodbye,", date(), "\n")
}

两个函数的效果为,会在进入和退出R 环境时分别执行:

  • 进入R

01. 自定义R 的启动环境 - 图4

  • 退出R

01. 自定义R 的启动环境 - 图5

R 的配置优先级

关于R 的配置文件,R 会按照Current project > Home > R_Home的目录顺序读取。

这里我习惯配置在用户Home 目录下。

R 提供了代码可以获取这几个目录:

# 当前工作目录
getwd()

# 用户家目录
~ # 可以直接使用相对路径获取
path.expand("~") # 也可以获得全路径

# R 安装目录
R.home()

自定义R库及R 位置

这里作者提供了一个模版:

#--------------------------------------------
# Set custom library and temp directory for R
# NOTE: please only change following 2 paths
#   Any Question, please email to 
#       Shixiang Wang <w_shixiang@163.com>
#--------------------------------------------
.CUSTOM_LIB = "D:/tools/R/R_Library" # set your custom library location
.TMP = "D:/tools/R/Rtmp"             # set a temp dir for R running
# please do not add '/' at the end !!!

if(!dir.exists(.CUSTOM_LIB)){
  dir.create(.CUSTOM_LIB)
}

.libPaths(c(.CUSTOM_LIB, .libPaths()))
message("Using library: ", .libPaths()[1])


if(dirname(tempdir()) != .TMP){
  if(!dir.exists(.TMP)) dir.create(.TMP)
  cat(paste0("TMPDIR = ", .TMP), file="~/.Renviron", sep = "\n")
}
message("Using temp directory: ", .TMP)