Search code examples
rr-box

Load all functions in one go using r box package


I am using the box package. In my project, I have a functions folder, with two functions saved in there: hello.r and goodbye.r

I can load them using the box package using:

box::use(functions/hello)
box::use(functions/goodbye)

The problem is that I potentially have dozens of .r files in the functions folder (one .r file for each function).

Is there a way of loading all the .r files in one go (whilst still using the box package) without having to repeat the box::use function many times?


Solution

  • Since box::use uses Non-Standard Evaluation (NSE) you have to transform strings into unevaluated language objects:

    rm(list = ls())
    ls()
    # character(0)
    
    rex <- "\\.[rR]$"
    fld <- "functions"
    
    fs::dir_tree(fld)
    # functions
    # ├── goodbye.R
    # └── hello.R
    
    fns <- list.files(fld, rex) |>     ## read all files in the folder
      gsub(rex, "", x = _) |>          ## drop extension
      paste(fld, . = _, sep = "/") |>  ## pre-pend folder
      lapply(str2lang)                 ## transform string into language object
    
    ## or (`tools` is a base package)
    # fns <- tools::list_files_with_exts(fld, "R") |> 
    #   tools::file_path_sans_ext() |>
    #   lapply(str2lang)
    
    ## call box::use with the the newly creataed list
    do.call(box::use, fns)
    ls()
    # [1] "fld"     "fns"     "goodbye" "hello"   "rex" 
    

    Update based on Friede's tip to use str2lang