Source another R script in the `bin/` directory

When a process runs, your base directory is the working directory and R files are not within the same folder. Instead, the R files have been added to the PATH variable, which means you can call them but they are not directly accessible using source or any other local file operations.

One potential solution is to add the bin/ path as a variable.

​If we have an R file in bin/ called source.R:

hello_world <- function() {
  print("Hello World!")
}

To source this file we can read the PATH variable, take the last value (which is the bin/ added by Nextflow), and import the source.R file from this path explicitly.

process IMPORT_R {
    container 'docker.io/library/r-base:4.3.1'

    output:
        stdout

    script:
    """
    #!/usr/bin/Rscript --vanilla

    path <- Sys.getenv("PATH") |> strsplit(":")
    bin_path <- tail(path[[1]], n=1)
    source(file.path(bin_path, "source.R"))

    hello_world()
    """
}

Another solution could be to combine your R scripts into one file or use the R file as an input to the process.

1 Like

I’ve been playing around with the box library, which attempts to solve this problem but I haven’t been able to get it to read the PATH automatically.

Still, it’s possible if you put your source R script in a subfolder in bin/:

> tree
β”œβ”€β”€ bin
β”‚   └── my_r_scripts
β”‚       └── source.R
└── main.nf

main.nf:

process RUN_R {
    debug true

    output:
    stdout

    script:
    """
    #!Rscript --vanilla

    # Set base path of Box library
    path <- Sys.getenv("PATH") |> strsplit(":")
    bin_path <- tail(path[[1]], n=1)
    options(box.path = bin_path)
 
    # Load hello_world from bin/my_r_scripts/source.R
    box::use(my_r_scripts/source[hello_world]) # Load function
    hello_world()
    """
}

workflow {
    RUN_R()
}
1 Like