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

前言

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

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

而我的R 呢?

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

真无情呀。

这里尝试修改一下。

编辑文件

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

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

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

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

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

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

  1. # start with welcome
  2. .First <- function(){
  3. message("Hello Peng!")
  4. message(paste0("Welcome at ", date()))
  5. # 配置install 命令使用的线程
  6. n <- parallel::detectCores()
  7. options(Ncpus = n-1)
  8. n2 <- getOption("Ncpus", 1L)
  9. message(paste0("We will use ", n2, " cores for installing.\n"))
  10. }
  11. # finish with goodbye
  12. .Last <- function(){
  13. cat("\n Goodbye,", date(), "\n")
  14. }

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

  • 进入R

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

  • 退出R

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

R 的配置优先级

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

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

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

  1. # 当前工作目录
  2. getwd()
  3. # 用户家目录
  4. ~ # 可以直接使用相对路径获取
  5. path.expand("~") # 也可以获得全路径
  6. # R 安装目录
  7. R.home()

自定义R库及R 位置

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

  1. #--------------------------------------------
  2. # Set custom library and temp directory for R
  3. # NOTE: please only change following 2 paths
  4. # Any Question, please email to
  5. # Shixiang Wang <w_shixiang@163.com>
  6. #--------------------------------------------
  7. .CUSTOM_LIB = "D:/tools/R/R_Library" # set your custom library location
  8. .TMP = "D:/tools/R/Rtmp" # set a temp dir for R running
  9. # please do not add '/' at the end !!!
  10. if(!dir.exists(.CUSTOM_LIB)){
  11. dir.create(.CUSTOM_LIB)
  12. }
  13. .libPaths(c(.CUSTOM_LIB, .libPaths()))
  14. message("Using library: ", .libPaths()[1])
  15. if(dirname(tempdir()) != .TMP){
  16. if(!dir.exists(.TMP)) dir.create(.TMP)
  17. cat(paste0("TMPDIR = ", .TMP), file="~/.Renviron", sep = "\n")
  18. }
  19. message("Using temp directory: ", .TMP)