### R Code Example: Task Construction and Properties Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Demonstrates constructing a new task object and retrieving its number of rows and columns. Load necessary packages with library() at the beginning of examples. ```r #' # construct a new task #' task = Task$new("iris", task_type = "classif", backend = iris) #' #' # retrieve the number of rows #' task$nrow #' #' # retrieve the number of columns #' task$ncol ``` -------------------------------- ### Install mlr3verse Meta-Package Source: https://github.com/mlr-org/mlr3/blob/main/README.md Installs the mlr3verse meta-package, which includes mlr3 and several essential extension packages, providing a comprehensive environment for getting started with mlr3. ```r install.packages("mlr3verse") ``` -------------------------------- ### Install mlr3 Development Version from GitHub Source: https://github.com/mlr-org/mlr3/blob/main/README.md Installs the development version of the mlr3 package directly from its GitHub repository using the 'pak' package manager. Ensure 'pak' is installed first. ```r # install.packages("pak") pak::pak("mlr-org/mlr3") ``` -------------------------------- ### Initialize Pre-commit Hooks Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide Use `precommit::use_precommit()` to set up pre-commit hooks for automated styling and other checks. This helps maintain code quality before commits. Ensure the precommit package is installed. ```r precommit::use_precommit() ``` -------------------------------- ### Install styler R package branch Source: https://github.com/mlr-org/mlr3/wiki/Editor-Setup Install the 'mlr-style' branch of the styler package to enable mlr3-specific styling. This is a prerequisite for using the mlr_style transformer. ```r remotes::install_github("pat-s/styler@mlr-style") ``` -------------------------------- ### Registering a new learner in mlr3 Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/mlr3.md Objects like learners must be registered in their respective dictionaries. This example shows how to add a new learner to the `mlr_learners` dictionary. ```r #' @include mlr_learners.R mlr_learners$add("classif.rpart", function() LearnerClassifRpart$new()) ``` -------------------------------- ### Breaking Change Footer Example Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/commit-messages.md Use the 'BREAKING CHANGE:' footer to indicate significant changes that may break compatibility. ```text BREAKING CHANGE: parameter 'x' has been removed ``` -------------------------------- ### Install mlr3 from CRAN Source: https://github.com/mlr-org/mlr3/blob/main/README.md Installs the latest stable release of the mlr3 package from the Comprehensive R Archive Network (CRAN). ```r install.packages("mlr3") ``` -------------------------------- ### Apply mlr3 Package Styling Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide Use `styler.mlr::style_pkg()` to apply the mlr3 code style to the entire package. Ensure the styler package is installed first. ```r styler.mlr::style_pkg() ``` -------------------------------- ### Apply mlr3 File Styling Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide Use `styler.mlr::style_file()` to apply the mlr3 code style to a specific file. Ensure the styler package is installed first. ```r styler.mlr::style_file() ``` -------------------------------- ### Implementing a read-only active binding in R6 Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/mlr3.md This example shows how to create a read-only active binding for a 'task_type' field. Any attempt to assign a value to this binding will raise an error using `assert_ro_binding()`. ```r task_type = function(rhs) { assert_ro_binding(rhs) private$.data$task_type }, ``` -------------------------------- ### Perform LTO Checks on C Functions Source: https://github.com/mlr-org/mlr3/wiki/C-Functions This bash script outlines the steps to perform Link-Time Optimization (LTO) checks on a package with C functions using a Docker container. It includes building the package, installing dependencies, and running R CMD check. ```bash rm -f src/*.o src/*.so docker run -v `pwd`:/package -it rhub/lto:latest /bin/bash cd package R CMD build . R -q -e "pak::pkg_install('deps::.', dependencies = TRUE)" R CMD check bbotk_1.7.0.9000.tar.gz --no-manual --no-build-vignettes ``` -------------------------------- ### Implementing a mutable active binding in R6 Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/mlr3.md Public fields in R6 classes are exposed as active bindings. This example demonstrates how to create a mutable binding for an 'id' field, which validates the input using `assert_id()` when assigned. ```r id = function(rhs) { if (missing(rhs)) { return(private$.id) } private$.id = assert_id(rhs) }, ``` -------------------------------- ### Perform GCC-ASAN Checks on C Functions Source: https://github.com/mlr-org/mlr3/wiki/C-Functions This bash script details the process for conducting GCC AddressSanitizer (ASAN) checks on a package containing C functions, utilizing a Docker container. It covers building the package, installing dependencies, and executing R CMD check. ```bash rm -f src/*.o src/*.so docker run -v `pwd`:/package -it rhub/gcc-asan:latest /bin/bash cd package R CMD build . R -q -e "pak::pkg_install('deps::.', dependencies = TRUE)" R CMD check bbotk_1.7.0.9000.tar.gz ---no-manual --no-build-vignettes ``` -------------------------------- ### Documenting R6 Class Methods with Roxygen Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-R6-Guide Demonstrates how to document a method within an R6 class using Roxygen tags for description, parameters, and return values. Ensure all sections end with punctuation and types are correctly formatted. ```r Param = R6Class("Param", public = list( ... #' @description #' Repeats this parameter n-times (by cloning). #' Each parameter is named "\[id\]_rep_\ específicamente" and gets the additional tag "\[id\]_rep". #' #' @param n (`integer(1)`). #' @return [ParamSet]. rep = function(n) { ... } ... ), ... ) ``` -------------------------------- ### Documenting R6 Class Constructor Parameters Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-R6-Guide Document constructor parameters using @param, specifying name, type, and description. Use \cr for line breaks and indentation for multi-line descriptions. ```r Param = R6Class("Param", public = list( ... #' @description #' Creates a new instance of this [R6][R6::R6Class] class. #' #' Note that this object is typically constructed via derived classes, #' e.g., [ParamDbl]. #' #' @param id (`character(1)`)\cr #' Identifier of the object. #' @param special_vals (`list()`)\cr #' Arbitrary special values this parameter is allowed to take, to make it #' feasible. This allows extending the domain of the parameter. Note that #' these values are only used in feasibility checks, neither in generating #' designs nor sampling. #' @param default (`any`)\cr #' Default value. Can be from the domain of the parameter or an element of #' `special_vals`. Has value [NO_DEF] if no default exists. `NULL` can be a #' valid default. #' @param tags (`character()`)\cr #' Arbitrary tags to group and subset parameters. Some tags serve a special #' purpose:\cr #' * "required" implies that the parameters has to be given when setting #' `values` in [ParamSet]. initialize = function(id, special_vals, default, tags) { ... }, ... ), ... ) ``` -------------------------------- ### Documenting R6 Constructor Arguments Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Document constructor arguments using @section Construction, providing type and description for each parameter. ```r #' @section Construction: #' ``` #' t = TaskSupervised$new(id, task_type, backend, target) #' ``` ``` ```r #' * `id` :: `character(1)`\cr #' Name of the task. ``` ```r #' * `backend` :: ([DataBackend] | `data.frame()` | ...)\cr #' Either a [DataBackend], or any object which is convertible to a DataBackend with `as_data_backend()`. #' E.g., a `data.frame()` will be converted to a [DataBackendDataTable]. ``` -------------------------------- ### Redocument Package with devtools Source: https://github.com/mlr-org/mlr3/blob/main/AGENTS.md Update package documentation, including NAMESPACE and Rd files, using Rscript and devtools::document(). ```bash Rscript -e "devtools::document()" ``` -------------------------------- ### Top-Level Documentation for R6 Objects Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-R6-Guide Use @title and @description for top-level documentation of R6 objects. Tags like @usage and @format are not needed. ```r #' @title Param Object #' #' @description #' Abstract base class for parameters. ``` -------------------------------- ### Documenting R6 Class Methods Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Document public methods using @section Methods, detailing the method signature, argument types, and return type. ```r #' * `missings(cols = NULL)`\cr #' `character()` -> named `integer()`\cr #' Returns the number of missing values observations for each columns in `cols`. #' Argument `cols` defaults to all columns with role "target" or "feature". ``` ```r #' * `data(rows = NULL, cols = NULL, format = NULL)`\cr #' (`integer()` | `character()`, `character()`, `character(1)`) -> `any`\cr #' Returns a slice of the data from the [DataBackend] in the format specified by `format` #' (depending on the [DataBackend], but usually a [data.table::data.table()]). #' Rows are subsetted to only contain observations with role "use". #' Columns are filtered to only contain features with roles "target" and "feature". #' If invalid `rows` or `cols` are specified, an exception is raised. ``` -------------------------------- ### Documenting S3 Methods for R6 Objects Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Document S3 methods applicable to R6 objects, following the same format as regular methods. ```r #' * `as.data.table(t)`\cr #' [Task] -> [data.table::data.table()]\cr #' Returns the data set as `data.table()`. ``` -------------------------------- ### Documenting R6 Class Fields Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-R6-Guide Document fields using @field, specifying name and type. Descriptions for fields set during construction should be concise, referencing parameter documentation. ```r Param = R6Class("Param", public = list( #' @field id (`character(1)`)\cr #' Identifier of the object. id = NULL, #' @field special_vals (`list()`)\cr #' Arbitrary special values this parameter is allowed to take. special_vals = NULL, #' @field default (`any`)\cr #' Default value. default = NULL, #' @field tags (`character()`)\cr #' Arbitrary tags to group and subset parameters. tags = NULL, ... ), ... ) ``` -------------------------------- ### Reformat NEWS.md for Release Source: https://github.com/mlr-org/mlr3/wiki/NEWS-formatting Before making a release, reformat the development entries into categorized sections for a clearer overview. This improves readability for users. ```markdown # dev Features: * feature A * feature B Bugfixes: * Bug A * Bug B ``` -------------------------------- ### Documenting R6 Class Active Bindings Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-R6-Guide Document active bindings using @field, specifying name and type. Provide a concise description for each active binding. ```r ... active = list( #' @field class (`character(1)`)\cr #' R6 class name. Read-only. class = function() class(self)[[1L]], #' @field is_number (`logical(1)`)\cr #' `TRUE` if the parameter is of type "dbl" or "int". is_number = function() self$class %in% c("ParamDbl", "ParamInt"), #' @field is_categ (`logical(1)`)\cr #' `TRUE` if the parameter is of type "fct" or "lgl". is_categ = function() self$class %in% c("ParamFct", "ParamLgl"), #' @field has_default (`logical(1)`)\cr #' Is there a default value? has_default = function() !is_nodefault(self$default), #' @field storage_type (`character(1)`)\cr #' Data type when values of this parameter are stored in a data table or sampled. ... ), ... ) ``` -------------------------------- ### Dynamic RStudio Addin Configuration Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide Conditionally set the `styler.addins_style_transformer` option based on the current working directory to apply the mlr3 style to mlr or paradox projects. This provides flexibility in styling different projects. ```r if (grepl("mlr", getwd()) || grepl("paradox", getwd())) { options(styler.addins_style_transformer = "styler.mlr::mlr_style()") } ``` -------------------------------- ### Configure styler addin for mlr3 projects Source: https://github.com/mlr-org/mlr3/wiki/Editor-Setup Append this option to your .Rprofile to ensure the 'mlr_style' is used by the styler addin in RStudio for mlr3 or paradox projects. This automatically applies the project's styling rules. ```r if (grepl("mlr", getwd()) || grepl("paradox", getwd())) { options(styler.addins_style_transformer = "mlr_style()") } ``` -------------------------------- ### Run All Package Tests Source: https://github.com/mlr-org/mlr3/blob/main/AGENTS.md Execute all tests defined in the package using Rscript and devtools::test(). ```bash Rscript -e "devtools::test()" ``` -------------------------------- ### Conventional Commit Format Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/commit-messages.md Follow this structure for all commit messages. The description should be concise and imperative. ```text (): [optional body] [optional footer(s)] ``` -------------------------------- ### Using mlr3misc utilities Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/mlr3.md mlr3core dependencies include `mlr3misc`, providing utility functions like `map()`, `map_chr()`, `invoke()`, and `calculate_hash()`. These can be used directly without the `::` namespace operator. ```r # Example usage (not directly from source, but illustrative of the text) # mlr3misc::map(list(1, 2, 3), function(x) x * 2) ``` -------------------------------- ### Load Learner and Set Hyperparameter Source: https://github.com/mlr-org/mlr3/blob/main/README.md Loads a specific classification learner ('classif.rpart') and sets its 'cp' hyperparameter to 0.01. This prepares the learner for training. ```r # load learner and set hyperparameter learner = lrn("classif.rpart", cp = .01) ``` -------------------------------- ### Run R Code with devtools Source: https://github.com/mlr-org/mlr3/blob/main/AGENTS.md Execute arbitrary R code within the package context using Rscript and devtools::load_all(). ```bash Rscript -e "devtools::load_all(); code" ``` -------------------------------- ### Perform 3-Fold Cross-Validation Source: https://github.com/mlr-org/mlr3/blob/main/README.md Set up a 3-fold cross-validation resampling strategy and run experiments. Results can be accessed and aggregated. ```r # 3-fold cross validation resampling = rsmp("cv", folds = 3L) # run experiments rr = resample(task_penguins, learner, resampling) # access results rr$score(measure)[, .(task_id, learner_id, iteration, classif.acc)] ``` ```r rr$aggregate(measure) ``` -------------------------------- ### Update Pre-commit Hooks Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide Run `precommit::autoupdate()` periodically to update the pre-commit hooks. This ensures you are using the latest versions and configurations. ```r precommit::autoupdate() ``` -------------------------------- ### Roxygen Include Tag for Class Inheritance Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Use the @include tag to specify source files for inherited classes within the same package, controlling collation order. ```r #' @include TaskSupervised.R ``` -------------------------------- ### Run rchk Checks on C Functions Source: https://github.com/mlr-org/mlr3/wiki/C-Functions This snippet demonstrates how to use the rchk tool via Docker to perform checks on packages with C functions. It involves building the package and then running the rchk Docker image against the built tarball. ```bash rm -f src/*.o src/*.so docker pull kalibera/rchk:latest mkdir package R CMD build . mv bbotk_1.7.0.9000.tar.gz package/ docker run -v `pwd`/package:/rchk/package kalibera/rchk:latest /rchk/package/bbotk_1.7.0.9000.tar.gz ``` -------------------------------- ### Create and Inspect a Classification Task Source: https://github.com/mlr-org/mlr3/blob/main/README.md Loads the mlr3 library and creates a classification learning task named 'task_penguins' from the 'palmerpenguins' dataset. The task is then printed to show its properties. ```r library(mlr3) # create learning task task_penguins = as_task_classif(species ~ ., data = palmerpenguins::penguins) task_penguins ``` -------------------------------- ### Documenting R6 Class Fields Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Document class fields using @section Fields, specifying the field type and its purpose. ```r #' @section Fields: #' * `formula` :: `formula()`\cr #' Constructs a [stats::formula], e.g. `[target] ~ [feature_1] + [feature_2] + ... + [feature_k]`, using #' the active features of the task. ``` -------------------------------- ### Check pkgdown Documentation Source: https://github.com/mlr-org/mlr3/blob/main/AGENTS.md Verify the integrity and correctness of pkgdown documentation using Rscript and pkgdown::check_pkgdown(). ```bash Rscript -e "pkgdown::check_pkgdown()" ``` -------------------------------- ### Load mlr3 Test Helpers Source: https://github.com/mlr-org/mlr3/wiki/Integrating-Ecosystem Source the mlr3 test helper functions for use in unit tests. This should typically be placed in `inst/testthat/helper.R`. ```r lapply(list.files(system.file("testthat", package = "mlr3"), pattern = "^helper.*[.]R$", full.names = TRUE), source) ``` -------------------------------- ### Roxygen Export and Internal Keywords Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Use '@export' to expose classes to users and '@keywords internal' to hide them from the documentation overview, indicating they are for internal package use. ```r #' @export #' @keywords internal ``` -------------------------------- ### Configure RStudio Addin for mlr3 Style Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide Set the `styler.addins_style_transformer` option in `.Rprofile` to use the mlr3 style transformer for RStudio addins. This ensures consistent styling within the IDE. ```r options(styler.addins_style_transformer = "styler.mlr::mlr_style()") ``` -------------------------------- ### Roxygen Format Tag for R6 Classes Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Use the @format tag to specify the class type, indicating if it's a base or derived R6 class. ```r #' @format [R6::R6Class] object. ``` ```r #' @format [R6::R6Class] object inheriting from [Task]/[TaskSupervised]. ``` -------------------------------- ### Map ALEFix to a keyboard shortcut in vim Source: https://github.com/mlr-org/mlr3/wiki/Editor-Setup Map the ALEFix command to a keyboard shortcut (e.g., F8) for convenient application of code styling within vim. This allows quick execution of the fixer. ```vimscript nmap (ale_fix) ``` -------------------------------- ### Check Package with R CMD check Source: https://github.com/mlr-org/mlr3/blob/main/AGENTS.md Perform a comprehensive check of the R package for errors, warnings, and notes using Rscript and devtools::check(). ```bash Rscript -e "devtools::check()" ``` -------------------------------- ### Defining hyperparameters with paradox Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/mlr3.md Hyperparameters for mlr3 objects are defined using `paradox::ps()`. Parameters must be tagged with 'train' or 'predict' to indicate when they are used. Use `self$param_set$get_values(tags = "train")` to retrieve values during training. ```r ps = ps( cp = p_dbl(0, 1, default = 0.01, tags = "train"), keep_model = p_lgl(default = FALSE, tags = "train") ) ``` -------------------------------- ### Train and Predict with a Learner Source: https://github.com/mlr-org/mlr3/blob/main/README.md Performs a train/test split on the 'task_penguins' task, trains the 'learner' on the training set, and then generates predictions on the test set. ```r # train/test split split = partition(task_penguins, ratio = 0.67) # train the model learner$train(task_penguins, split$train_set) # predict data prediction = learner$predict(task_penguins, split$test_set) ``` -------------------------------- ### Add Commit Entries to NEWS.md Source: https://github.com/mlr-org/mlr3/wiki/NEWS-formatting During development, add commit entries as simple bullet points under a development section. This format is for internal tracking. ```markdown # dev * feat: feature A * feat: feature B * fix: Bug A * fix: Bug B ... ``` -------------------------------- ### Run Filtered Package Tests Source: https://github.com/mlr-org/mlr3/blob/main/AGENTS.md Execute tests that match a specific filter pattern using Rscript and devtools::test(). Useful for running tests related to a particular feature or file. ```bash Rscript -e "devtools::test(filter = '^{name}')" ``` -------------------------------- ### Identify Slow Test Files in R Source: https://github.com/mlr-org/mlr3/wiki/CRAN-Parallelization This script iterates through test files, measures their execution time, and flags those where CPU time significantly exceeds elapsed time, indicating potential parallelization issues. ```r files = list.files("tests/testthat", "test_", full.names = TRUE) for (file in files) { time = system.time(test_file(file)) ratio = time[1] / time[3] if (ratio > 2) { print(time) stopf("Test file %s had CPU time %f times elapsed time", file, ratio) } } ``` -------------------------------- ### Avoid Double Colon for Imported Functions in MLR3 Extensions Source: https://github.com/mlr-org/mlr3/wiki/Style-Guide When extending MLR3, import functions directly and call them without the package namespace qualifier (::). Use '::' only for suggested packages or to resolve name clashes. ```r mlr3::train() mlr3::predict() mlr3::resample() ``` ```r train() predict() resample() ``` -------------------------------- ### Roxygen Title Tag Source: https://github.com/mlr-org/mlr3/wiki/Roxygen-Guide Use the @title tag for the class title, following title case conventions. ```r #' @title Regression Task ``` -------------------------------- ### Structured error handling in mlr3 Source: https://github.com/mlr-org/mlr3/blob/main/extra-rules/mlr3.md mlr3 uses structured error and warning functions from `mlr3misc`, such as `error_config()` and `warning_input()`. These functions support `sprintf`-style formatting for dynamic error messages. ```r # Example usage (not directly from source, but illustrative of the text) # error_input("Invalid parameter value: %s", "some_value") ```