「R」R 的安装与配置

本文提供对 r 的安装与配置指南,专为 windows 用户设计,其他系统的用户可参考类似步骤。作为一个经验丰富的用户,我希望通过本文帮助初学者避免常见问题,并为其他读者提供有用的见解。

安装 R 主要包括以下三个步骤:

  1. 安装 R:从 https://www./link/453c5ee2c6f6cbdddf021c36677eedc4 下载并安装。
  2. 安装 RStudio(可选):从 https://www./link/f40ed67587440c64e5b3881297d5c827 下载并安装。
  3. 安装 Rtools:用于编译源码包,尤其是包含其他语言编写的包,从 https://www./link/d750dbc5c4510c96e92e256136bdeb73 下载并安装。

基于我多次安装 R 及解决错误的经验,以下是一些重要建议:

  • 避免将 R 安装在
    Program Files
    目录下。建议在 C 盘或其他盘(如有固态硬盘,优先选择固态硬盘)创建一个专门的目录,如
    C:/Tools
    ,用于安装 R、R 包和 Rtools。
  • 如果你的电脑是 64 位的,安装时可以忽略 32 位选项。
  • 安装过程中涉及到添加环境变量或路径时,请选择添加选项。其余步骤按默认设置继续即可。

默认情况下,Windows R 使用用户文档目录作为家目录,系统指定的临时目录作为临时目录,安装路径下的

R版本/library
目录作为 R 包存储目录。如果使用默认设置,可能会遇到以下问题:

  • 安装包过多或使用电脑管家等管理软件时,系统临时目录可能被锁定,导致 RStudio 无法读写。
  • 更新 R 版本时,需要重新安装所有包,这对于安装了数百个包的用户来说尤为麻烦。

为避免这些问题,你可以在安装 R 和 RStudio 后,通过自定义临时目录和包目录来解决。操作步骤如下:

在 RStudio 中打开 R 控制台,输入以下命令:

file.edit("~/.Rprofile")

在打开的

.Rprofile
文件中添加以下内容:

#--------------------------------------------#
# Set custom library and temp directory for R#
# NOTE: please only change following 2 paths#
#   Any Question, please email to            #
#       Shixiang Wang            #
#--------------------------------------------#
.CUSTOM_LIB = "C:/Tools/R/R_Library" # set your custom library location.
.TMP = "C:/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)
#---------------------------------------------------#
# pacman is optional, you can delete following code #
# If you wanna use pacman, please read:             #
#   # 
# Basically,                                         #
# #1, you can use 'p_load' to load multiple package into R
#       like p_load(data.table, dplyr)
# #2, you can use 'p_get' just to install package
# #3, you can use 'p_update' to update all packages #
#---------------------------------------------------#
if(!require(pacman)){
    install.packages("pacman", dependencies = TRUE)
}
library(pacman)
#----------------------------------------------------#

你可以根据需要修改以下路径:

.CUSTOM_LIB = "C:/Tools/R/R_Library" # set your custom library location.
.TMP = "C:/Tools/R/Rtmp"             # set a temp dir for R running
                                     # please do not add '/' at the end !!!

pacman
代码块是可选的,它是
library()
函数的替代品,使用更简便。更多信息请参考 https://www./link/8a8e04cd95933b42915d5f7897d0f96f。

保存修改后,重启 RStudio 或通过菜单栏中的 Session -> Restart R 重新启动 R。每次启动时,R 会输出包的存储路径和临时路径,方便你确认设置。

这样,当你升级 R 时,只需重新安装 R-base,R 包会保留在原位置。你最多只需在控制台运行以下命令来更新所有包:

p_update()