Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load all functions in one go using r box package

Tags:

r

r-box

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?

like image 207
Basil Avatar asked Oct 21 '25 05:10

Basil


1 Answers

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

like image 141
thothal Avatar answered Oct 23 '25 19:10

thothal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!