zl程序教程

您现在的位置是:首页 >  其他

当前栏目

10. R studio/R 工具指南(九:配置R 的启动文件)

2023-04-18 14:58:07 时间

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

前言

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

而我的R 呢?

真无情呀。

怎么样让我的R 也可以乖乖的欢迎主人呢?

这里尝试修改一下。

编辑文件

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

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

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

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

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

# 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.
"))
}


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

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

  • 进入R

image.png

  • 退出R

image.png

除此之外,你还可以将常用的几个R 包配置在启动文件中,这样可以减少每次脚本中的重复调用。

(不过如果是同他人分享脚本的话,还是需要注意的)

R 的配置优先级

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

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

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

# 当前工作目录
getwd()

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

# R 安装目录
R.home()

其他模版

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

#--------------------------------------------
# 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 = "
")
}
message("Using temp directory: ", .TMP)