You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Github Actions中R脚本执行失败:无法找到已缓存的R包

问题分析与解决方案

核心问题

你的缓存配置存在两个关键疏漏:

  1. 安装R依赖时,未指定包安装到缓存路径${{ github.workspace }}/R/Rlibs,导致首次运行的包被安装到R默认的系统库路径,缓存目录实际为空。
  2. 运行R脚本时,R未加载缓存路径,即使缓存恢复也无法找到其中的包(即便缓存非空)。

首次运行脚本成功是因为包在默认库路径,而缓存创建的是空目录;第二次运行缓存命中(空目录),跳过安装后,新Runner环境的默认库没有httr,因此报错。

修改后的YAML配置(推荐方案)

通过设置全局环境变量指定R库路径,确保安装和运行时都使用缓存目录:

jobs:
  your-job-name:
    runs-on: ubuntu-latest
    # 全局设置R库路径为缓存目录
    env:
      R_LIBS_USER: ${{ github.workspace }}/R/Rlibs
    steps:
      - uses: actions/checkout@v4

      - name: Cache R packages
        uses: actions/cache@v3
        id: cache
        if: runner.os != 'Windows'
        with:
          path: ${{ env.R_LIBS_USER }}
          key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }}
          restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-

      - name: Create library directory
        run: mkdir -p ${{ env.R_LIBS_USER }}
        shell: bash

      - name: Install dependencies
        if: steps.cache.outputs.cache-hit != 'true'
        run: |
          remotes::install_deps(dependencies = TRUE)
        shell: Rscript {0}

      - name: Run R Script
        run: |
          source("R/script.R")
        shell: Rscript {0} 

关键修改说明

  • 新增env字段设置R_LIBS_USER,让R默认将包安装到缓存目录,运行时也优先从该目录加载包。
  • 添加Create library directory步骤,确保缓存目录存在,避免安装时出错。
  • 缓存路径改用环境变量引用,保持配置一致性。

替代方案(修改.Rprofile)

如果不想用全局环境变量,可通过修改.Rprofile让R加载缓存路径:

- name: Cache R packages
        uses: actions/cache@v3
        id: cache
        if: runner.os != 'Windows'
        with:
          path: ${{ github.workspace }}/R/Rlibs
          key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }}
          restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-

      - name: Configure R library path
        run: |
          dir.create("R/Rlibs", recursive = TRUE, showWarnings = FALSE)
          # 修改.Rprofile,让R启动时加载缓存路径
          echo "options(repos = c(CRAN = 'https://cloud.r-project.org/'))" >> .Rprofile
          echo ".libPaths(c('${{ github.workspace }}/R/Rlibs', .libPaths()))" >> .Rprofile
        shell: bash

      - name: Install dependencies
        if: steps.cache.outputs.cache-hit != 'true'
        run: |
          # 指定安装到缓存路径
          remotes::install_deps(dependencies = TRUE, lib = "${{ github.workspace }}/R/Rlibs")
        shell: Rscript {0}

      - name: Run R Script
        run: |
          source("R/script.R")
        shell: Rscript {0} 

内容的提问来源于stack exchange,提问作者mjp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:57:13