### Access package environments using strings Source: https://rlang.r-lib.org/reference/as_environment Provides a convenient way to get the environment of a specified package. For example, `as_environment("base")` returns the base package environment, and `as_environment("rlang")` returns the rlang package environment. ```r # With strings it is a handy shortcut for pkg_env(): as_environment("base") #> as_environment("rlang") #> #> attr(,"name") #> [1] "package:rlang" #> attr(,"path") #> [1] "/home/runner/work/_temp/Library/rlang" ``` -------------------------------- ### Enable global prompt for package installation Source: https://rlang.r-lib.org/reference/global_prompt_install Call `global_prompt_install()` with `enable = TRUE` to activate the feature. This will cause missing packages to be prompted for installation instead of causing a hard error. ```r global_prompt_install(enable = TRUE) ``` -------------------------------- ### Get tail environment with env_tail() Source: https://rlang.r-lib.org/reference/env_parent Demonstrates how to get the tail environment of the global environment using env_tail(). ```r env_tail(global_env()) #> ``` -------------------------------- ### global_prompt_install Source: https://rlang.r-lib.org/reference/global_prompt_install Controls whether to globally prompt the user to install missing packages. ```APIDOC ## global_prompt_install ### Description Controls whether to globally prompt the user to install missing packages. When enabled, `packageNotFoundError` thrown by `loadNamespace()` will cause a user prompt to install the missing package and continue without interrupting the current program. ### Usage ```r global_prompt_install(enable = TRUE) ``` ### Arguments - enable (logical): Whether to enable or disable global handling. ``` -------------------------------- ### Example of enquo() and enquos() with injection Source: https://rlang.r-lib.org/reference/enquo Demonstrates how enquo() and enquos() enable injection and embracing for users, allowing for dynamic function behavior. ```APIDOC ## Examples ```r # `enquo()` defuses the expression supplied by your user f <- function(arg) { enquo(arg) } f(1 + 1) #> #> expr: ^1 + 1 #> env: 0x55f05c9641e8 # `enquos()` works with arguments and dots. It returns a list of # expressions f <- function(...) { enquos(...) } f(1 + 1, 2 * 10) #> > #> #> [[1]] #> #> expr: ^1 + 1 #> env: 0x55f05c9641e8 #> #> [[2]] #> #> expr: ^2 * 10 #> env: 0x55f05c9641e8 #> # `enquo()` and `enquos()` enable _injection_ and _embracing_ for # your users g <- function(arg) { f({{ arg }} * 2) } g(100) #> > #> #> [[1]] #> #> expr: ^(^100) * 2 #> env: 0x55f05ef32418 #> column <- sym("cyl") g(!!column) #> > #> #> [[1]] #> #> expr: ^(^cyl) * 2 #> env: 0x55f05bda2e08 #> ``` ``` -------------------------------- ### Setup RMarkdown document for entracing Source: https://rlang.r-lib.org/reference/global_entrace Include this setup chunk in an RMarkdown document before the first error or warning to promote them to rlang conditions with backtraces. It's recommended to also configure warning and error report options. ```r rlang::global_entrace() options(rlang_backtrace_on_warning_report = "full") options(rlang_backtrace_on_error_report = "full") ``` -------------------------------- ### Examples Source: https://rlang.r-lib.org/reference/on_load Illustrates how to use `on_load()` and `on_package_load()` for tasks like registering S3 methods, assigning objects dynamically, and executing actions when other packages are loaded. ```APIDOC ## Examples ```r quote({ # First add `run_on_load()` to your `.onLoad()` hook, # then use `on_load()` anywhere in your package .onLoad <- function(lib, pkg) { run_on_load() } # Register a method on load on_load({ s3_register("foo::bar", "my_class") }) # Assign an object on load var <- NULL on_load({ var <- foo() }) # To use `on_package_load()` at top level, wrap it in `on_load()` on_load({ on_package_load("foo", message("foo is loaded")) }) # In functions it can be called directly f <- function() on_package_load("foo", message("foo is loaded")) }) ``` ``` -------------------------------- ### Install rlang Development Version from GitHub Source: https://rlang.r-lib.org/llms.txt Use this command to install the development version of the rlang package from GitHub using the 'pak' package manager. ```r # install.packages("pak") pak::pkg_install("r-lib/rlang") ``` -------------------------------- ### Get parent environment with env_parent() Source: https://rlang.r-lib.org/reference/env_parent Demonstrates how to get the parent environment of the global environment using env_parent(). ```r env_parent(global_env()) #> #> attr(,"name") #> [1] "package:rlang" #> attr(,"path") #> [1] "/home/runner/work/_temp/Library/rlang" ``` -------------------------------- ### check_installed Source: https://rlang.r-lib.org/reference/is_installed Checks if packages are installed and prompts the user to install missing ones in interactive sessions. In non-interactive sessions or if the user declines, evaluation is aborted. Can be configured via global options. ```APIDOC ## check_installed ### Description Checks that packages are installed. In interactive sessions, asks the user whether to install missing packages. If the user accepts, the packages are installed. If the session is non-interactive or if the user chooses not to install the packages, the current evaluation is aborted. ### Usage ```r check_installed( pkg, reason = NULL, ..., version = NULL, compare = NULL, action = NULL, call = caller_env() ) ``` ### Arguments - pkg: The package names. Can include version requirements, e.g. `"pkg (>= 1.0.0)"`. - reason: Optional string indicating why is `pkg` needed. Appears in error messages (if non-interactive) and user prompts (if interactive). - ...: These dots must be empty. - version: Minimum versions for `pkg`. If supplied, must be the same length as `pkg`. `NA` elements stand for any versions. - compare: A character vector of comparison operators to use for `version`. If supplied, must be the same length as `version`. If `NULL`, `>=` is used as default for all elements. `NA` elements in `compare` are also set to `>=` by default. - action: An optional function taking `pkg` and `...` arguments. It is called by `check_installed()` when the user chooses to update outdated packages. The function is passed the missing and outdated packages as a character vector of names. - call: The execution environment of a currently running function, e.g. [`caller_env()`](https://rlang.r-lib.org/reference/stack.md). The function will be mentioned in error messages as the source of the error. See the `call` argument of [`abort()`](https://rlang.r-lib.org/reference/abort.md) for more information. ### Value `check_installed()` either doesn't return or returns `NULL`. ### Handling package not found errors `check_installed()` signals error conditions of class `rlib_error_package_not_found`. The error includes `pkg` and `version` fields. They are vectorised and may include several packages. The error is signalled with a `rlib_restart_package_not_found` restart on the stack to allow handlers to install the required packages. To do so, add a [calling handler](https://rdrr.io/r/base/conditions.html) for `rlib_error_package_not_found`, install the required packages, and invoke the restart without arguments. This restarts the check from scratch. The condition is not signalled in non-interactive sessions, in the restarting case, or if the `rlib_restart_package_not_found` user option is set to `FALSE`. ``` -------------------------------- ### is_installed Source: https://rlang.r-lib.org/reference/is_installed Checks if packages are installed without user interaction. Returns TRUE if all specified packages are installed, FALSE otherwise. It may load installed packages but will not attach them. ```APIDOC ## is_installed ### Description Checks if packages are installed. Returns `TRUE` or `FALSE` depending on whether the packages are installed. Does not interact with the user. ### Usage ```r is_installed(pkg, ..., version = NULL, compare = NULL) ``` ### Arguments - pkg: The package names. Can include version requirements, e.g. `"pkg (>= 1.0.0)"`. - ...: These dots must be empty. - version: Minimum versions for `pkg`. If supplied, must be the same length as `pkg`. `NA` elements stand for any versions. - compare: A character vector of comparison operators to use for `version`. If supplied, must be the same length as `version`. If `NULL`, `>=` is used as default for all elements. `NA` elements in `compare` are also set to `>=` by default. ### Value `is_installed()` returns `TRUE` if *all* package names provided in `pkg` are installed, `FALSE` otherwise. ### Examples ```r is_installed("utils") #> [1] TRUE is_installed(c("base", "ggplot5")) #> [1] FALSE is_installed(c("base", "ggplot5"), version = c(NA, "5.1.0")) #> [1] FALSE ``` ``` -------------------------------- ### Install rlang from CRAN Source: https://rlang.r-lib.org/llms.txt Use this command to install the released version of the rlang package from CRAN. ```r install.packages("rlang") ``` -------------------------------- ### Check package installation with version requirements Source: https://rlang.r-lib.org/reference/is_installed Use `is_installed()` with `version` and `compare` arguments to check for specific package versions. NA in `version` or `compare` indicates no specific requirement for that package. ```r is_installed(c("base", "ggplot5"), version = c(NA, "5.1.0")) #> [1] FALSE ``` -------------------------------- ### Example of enquo() defusing an argument Source: https://rlang.r-lib.org/reference/enquo Demonstrates how `enquo()` captures the expression passed to its argument. The output shows the captured expression and its environment. ```r f <- function(arg) { enquo(arg) } f(1 + 1) #> #> expr: ^1 + 1 #> env: 0x55f05c9641e8 ``` -------------------------------- ### enquo() and enquos() enable injection and embracing Source: https://rlang.r-lib.org/reference/enquo Shows how `enquo()` and `enquos()` facilitate injection and embracing, allowing users to dynamically insert expressions or symbols into function calls. The example uses `{{ arg }}` for embracing and `!!sym("cyl")` for injection. ```r g <- function(arg) { f({{ arg }} * 2) } g(100) #> > #> #> [[1]] #> #> expr: ^(^100) * 2 #> env: 0x55f05ef32418 ``` ```r column <- sym("cyl") g(!!column) #> > #> #> [[1]] #> #> expr: ^(^cyl) * 2 #> env: 0x55f05bda2e08 ``` -------------------------------- ### Get package environment names and objects Source: https://rlang.r-lib.org/reference/search_envs Use `pkg_env_name()` to construct the search path name for a package (e.g., "package:rlang") and `search_env()` to retrieve the corresponding environment. `pkg_env()` provides a direct shortcut to get the package's scoped environment. ```r pkg_env_name("rlang") #> [1] "package:rlang" search_env(pkg_env_name("rlang")) #> #> attr(,"name") #> [1] "package:rlang" #> attr(,"path") #> [1] "/home/runner/work/_temp/Library/rlang" ``` ```r pkg_env("utils") #> #> attr(,"name") #> [1] "package:utils" #> attr(,"path") #> [1] "/opt/R/4.5.3/lib/R/library/utils" ``` -------------------------------- ### Compare seq2 with base::seq Source: https://rlang.r-lib.org/reference/seq2 Demonstrates the difference in behavior between `seq2()` and `base::seq()` when the start is greater than the end. ```r seq(10, 2) #> [1] 10 9 8 7 6 5 4 3 2 ``` -------------------------------- ### Example usage of check_bool Source: https://rlang.r-lib.org/reference/check_type_scalar Demonstrates the correct usage of `check_bool()` with a TRUE value and how it throws an error for a numeric input. ```r check_bool(TRUE) try(check_bool(1)) ``` -------------------------------- ### Example of enquos() defusing multiple arguments Source: https://rlang.r-lib.org/reference/enquo Illustrates `enquos()` capturing multiple arguments, including arithmetic expressions, into a list of quosures. Each quosure contains the expression and its environment. ```r f <- function(...) { enquos(...) } f(1 + 1, 2 * 10) #> > #> #> [[1]] #> #> expr: ^1 + 1 #> env: 0x55f05c9641e8 #> #> [[2]] #> #> expr: ^2 * 10 #> env: 0x55f05c9641e8 ``` -------------------------------- ### Check if multiple packages are installed Source: https://rlang.r-lib.org/reference/is_installed Provide a character vector to `is_installed()` to check for the presence of multiple packages. It returns FALSE if any package is missing. ```r is_installed(c("base", "ggplot5")) #> [1] FALSE ``` -------------------------------- ### Colorize local quosures with expr_print() Source: https://rlang.r-lib.org/reference/expr_print Demonstrates how expr_print() colorizes quosures from local environments. Ensure the 'crayon' package is installed for color output. ```r local_quo <- local(quo(foo)) expr_print(local_quo) #> ^foo ``` ```r wrapper_quo <- local(quo(bar(!!local_quo, baz))) expr_print(wrapper_quo) #> ^bar(^foo, baz) ``` -------------------------------- ### State Management Functions Source: https://rlang.r-lib.org/llms.txt Functions for checking package installation status and R's interactive state, as well as managing global options. ```APIDOC ## is_installed() ### Description Checks if packages are installed in any of the libraries. ### Method N/A (R function) ### Endpoint N/A ### Parameters None explicitly documented for direct user call. ### Request Example N/A ### Response N/A ## is_interactive() ### Description Checks if R is running interactively. ### Method N/A (R function) ### Endpoint N/A ### Parameters None explicitly documented for direct user call. ### Request Example N/A ### Response N/A ## local_options() ### Description Temporarily changes global options. ### Method N/A (R function) ### Endpoint N/A ### Parameters None explicitly documented for direct user call. ### Request Example N/A ### Response N/A ## on_load() ### Description Runs expressions when a package is loaded. ### Method N/A (R function) ### Endpoint N/A ### Parameters None explicitly documented for direct user call. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Get names of symbols bound in an environment Source: https://rlang.r-lib.org/reference/env_names Use `env_names()` to get a character vector of all object names from an environment. This includes names that start with a dot. ```r env <- env(a = 1, b = 2) env_names(env) #> [1] "a" "b" ``` -------------------------------- ### Sum byte sizes Source: https://rlang.r-lib.org/reference/bytes-class You can perform arithmetic operations like summation on vectors of parsed byte sizes. This example sums '1MB', '5MB', and '500KB'. ```r sum(parse_bytes(c("1MB", "5MB", "500KB"))) #> [1] 6.50 MB ``` -------------------------------- ### Get environment names Source: https://rlang.r-lib.org/reference/env_names `env_names()` returns object names from an environment `env` as a character vector. All names are returned, even those starting with a dot. ```APIDOC ## env_names() ### Description Returns object names from an environment `env` as a character vector. All names are returned, even those starting with a dot. ### Usage ```r env_names(env) ``` ### Arguments * `env`: An environment. ### Value A character vector of object names. ### Examples ```r env <- env(a = 1, b = 2) env_names(env) #> [1] "a" "b" ``` ``` -------------------------------- ### Compare new_quosure() and quo() Source: https://rlang.r-lib.org/reference/new_quosure Demonstrates that `new_quosure()` and `quo()` produce equivalent results when creating a quosure from an expression and the current environment. ```r new_quosure(quote(foo), current_env()) ``` ```r quo(foo) ``` -------------------------------- ### Get Current Frame Properties Source: https://rlang.r-lib.org/reference/stack Use these functions to retrieve properties of the current execution frame. `current_call()` gets the call, `current_fn()` gets the function, and `current_env()` gets the environment. ```r current_call() current_fn() current_env() ``` -------------------------------- ### Create and Inspect a Quosure Source: https://rlang.r-lib.org/reference/quosure-tools Demonstrates creating a quosure, accessing its components, and modifying them. It also shows how to test if an object is a quosure and use type-specific predicates. ```r quo <- quo(my_quosure) quo #> #> expr: ^my_quosure #> env: 0x55f059f9c938 # Access and set the components of a quosure: quo_get_expr(quo) #> my_quosure quo_get_env(quo) #> quo <- quo_set_expr(quo, quote(baz)) quo <- quo_set_env(quo, empty_env()) quo #> #> expr: ^baz #> env: empty # Test wether an object is a quosure: is_quosure(quo) #> [1] TRUE # If it is a quosure, you can use the specialised type predicates # to check what is inside it: quo_is_symbol(quo) #> [1] TRUE quo_is_call(quo) #> [1] FALSE quo_is_null(quo) #> [1] FALSE ``` -------------------------------- ### Get key/value from weak reference object Source: https://rlang.r-lib.org/reference/wref_key Use `wref_key()` to get the key and `wref_value()` to get the value from a weak reference object. ```r wref_key(x) ``` ```r wref_value(x) ``` -------------------------------- ### Create a quosure with as_quosure() Source: https://rlang.r-lib.org/reference/new_quosure Use `as_quosure()` to create a quosure. It preserves input if it's already a quosure. An environment must be supplied for naked expressions. ```r as_quosure(quo(foo)) ``` ```r env <- env(var = "thing") as_quosure(quote(var), env) ``` ```r as_quosure(~foo, env) ``` ```r as_quosure(~foo) ``` ```r try( as_quosure(quote(var)) ) ``` -------------------------------- ### Get Caller Frame Properties Source: https://rlang.r-lib.org/reference/stack Use these functions to retrieve properties of calling frames. Specify the number of callers to go back with the `n` argument. `caller_call()` gets the call, `caller_fn()` gets the function, and `caller_env()` gets the environment. ```r caller_call(n = 1) caller_fn(n = 1) caller_env(n = 1) ``` -------------------------------- ### Usage of inherits_any, inherits_all, inherits_only Source: https://rlang.r-lib.org/reference/inherits_any Demonstrates the basic function signatures for checking object inheritance. ```r inherits_any(x, class) inherits_all(x, class) inherits_only(x, class) ``` -------------------------------- ### Generate sequence from start to end Source: https://rlang.r-lib.org/reference/seq2 Use `seq2()` to create a sequence of integers from a starting point to an ending point. Returns an empty vector if the start is greater than the end. ```r seq2(2, 10) #> [1] 2 3 4 5 6 7 8 9 10 ``` ```r seq2(10, 2) #> integer(0) ``` -------------------------------- ### Get Specific Frame Properties Source: https://rlang.r-lib.org/reference/stack Use these functions to retrieve properties of a specific frame identified by its environment. `frame_call()` gets the call, and `frame_fn()` gets the function. The `frame` argument should be an environment, typically obtained from `caller_env()`. ```r frame_call(frame = caller_env()) frame_fn(frame = caller_env()) ``` -------------------------------- ### Create a basic function Source: https://rlang.r-lib.org/reference/new_function Demonstrates creating a simple function with no arguments and a fixed body. ```r f <- function() letters g <- new_function(NULL, quote(letters)) identical(f, g) ``` -------------------------------- ### Create function with named arguments and default values Source: https://rlang.r-lib.org/reference/new_function Shows how to create functions with parameters using `list()` or `pairlist2()` for default arguments. ```r new_function(list(x = 10), quote(x)) ``` ```r new_function(pairlist2(x = 10), quote(x)) ``` -------------------------------- ### Typed Vector Construction vs c() Source: https://rlang.r-lib.org/reference/vector-construction Demonstrates the equivalence of typed constructors to c() for basic vector creation and highlights the explicit type control they offer. ```r c(TRUE, FALSE) #> [1] TRUE FALSE lgl(TRUE, FALSE) #> [1] TRUE FALSE ``` -------------------------------- ### Check if a single package is installed Source: https://rlang.r-lib.org/reference/is_installed Use `is_installed()` to check if a specific package is available. It returns TRUE if installed, FALSE otherwise. ```r is_installed("utils") #> [1] TRUE ``` -------------------------------- ### Fetching an object from a parent environment with env_get Source: https://rlang.r-lib.org/reference/env_get Demonstrates how to fetch an object (`foo`) from a parent environment when it's not directly present in the current environment. The `inherit = TRUE` argument enables searching parent environments. ```r parent <- child_env(NULL, foo = "foo") env <- child_env(parent, bar = "bar") # This throws an error because `foo` is not directly defined in env: # env_get(env, "foo") # However `foo` can be fetched in the parent environment: env_get(env, "foo", inherit = TRUE) #> [1] "foo" ``` -------------------------------- ### Get Namespace Environment Name Source: https://rlang.r-lib.org/reference/ns_env Use `ns_env_name()` to get the name of the namespace environment. This is useful for identifying which package's namespace is being referenced. ```r ns_env_name(x = caller_env()) ``` -------------------------------- ### Get Namespace Environment Source: https://rlang.r-lib.org/reference/ns_env Use `ns_env()` to get the namespace environment of a package or the current environment by default. It searches the environment ancestry for a namespace. ```r ns_env(x = caller_env()) ``` -------------------------------- ### Create environment inheriting from current Source: https://rlang.r-lib.org/reference/env Use `env()` to create a new environment that inherits from the current environment by default. You can populate it with named objects. ```r env <- env(a = 1, b = "foo") env$b identical(env_parent(env), current_env()) ``` -------------------------------- ### Get environment label for anonymous environments Source: https://rlang.r-lib.org/reference/env_name Use env_label() to get a label for anonymous environments, which defaults to their memory address. env_name() returns an empty string for these. ```r env_name(env()) #> [1] "" env_label(env()) #> [1] "0x55f05f066ed0" ``` -------------------------------- ### Get environment name Source: https://rlang.r-lib.org/reference/env_name Use env_name() to get the name of an environment. It returns specific labels for common environments like global, namespace, and empty environments. ```r env_name(global_env()) #> [1] "global" env_name(ns_env("rlang")) #> [1] "namespace:rlang" ``` -------------------------------- ### Basic injection with inject() Source: https://rlang.r-lib.org/reference/inject Demonstrates that `inject()` evaluates its argument with injection support, showing equivalence to direct evaluation. ```r 2 * 3 #> [1] 6 inject(2 * 3) #> [1] 6 inject(!!2 * !!3) #> [1] 6 ``` -------------------------------- ### Store and retrieve a global option Source: https://rlang.r-lib.org/reference/local_options Use push_options() to set a global option and peek_option() to retrieve its value. This is useful for setting default configurations. ```r push_options(my_option = 10) peek_option("my_option") ``` -------------------------------- ### Clone an environment with env_clone() Source: https://rlang.r-lib.org/reference/env_clone Demonstrates creating a clone of an environment and modifying it without affecting the original. Use `env_clone()` to create an independent copy. ```r env <- env(a = 1, b = 2) clone <- env_clone(env) env_print(clone) #> #> Parent: #> Bindings: #> • a: #> • b: env_print(env) #> #> Parent: #> Bindings: #> • a: #> • b: ``` ```r env_bind(clone, a = "foo", c = 3) env_print(clone) #> #> Parent: #> Bindings: #> • a: #> • b: #> • c: env_print(env) #> #> Parent: #> Bindings: #> • a: #> • b: ``` -------------------------------- ### Get last error trace - rlang Source: https://rlang.r-lib.org/reference/last_error Use `last_trace()` as a shortcut to get the backtrace stored in the last error. By default, technical calls are hidden; set `drop = FALSE` to see the full backtrace. ```r last_trace(drop = NULL) ``` -------------------------------- ### Create function with empty arguments Source: https://rlang.r-lib.org/reference/new_function Demonstrates how to define parameters without default values using `pairlist2()` or `exprs()`. ```r new_function(pairlist2(x = , y = 5 + 5), quote(x + y)) ``` ```r new_function(exprs(x = , y = 5 + 5), quote(x + y)) ``` -------------------------------- ### Basic Usage of eval_bare() Source: https://rlang.r-lib.org/reference/eval_bare Demonstrates the basic usage of eval_bare() by evaluating a simple expression in a custom environment. This is similar to base::eval() but requires explicit environment creation. ```r eval_bare(quote(foo), env(foo = "bar")) ``` -------------------------------- ### Get environment length Source: https://rlang.r-lib.org/reference/env_names `env_length()` returns the number of bindings in an environment. ```APIDOC ## env_length() ### Description Returns the number of bindings in an environment. ### Usage ```r env_length(env) ``` ### Arguments * `env`: An environment. ### Value An integer representing the number of bindings. ``` -------------------------------- ### Get and Set Environment Objects Source: https://rlang.r-lib.org/llms.txt Functions for retrieving and modifying objects within an environment. ```APIDOC ## Get and Set Environment Objects ### Description Functions for retrieving and modifying objects within an environment. ### Functions - `get_env()`: Gets the environment of an object. - `set_env()`: Sets the environment of an object. - `env_poke_parent()`: Modifies the parent environment of an object. ``` -------------------------------- ### seq2_along(from, x) Source: https://rlang.r-lib.org/reference/seq2 Generates a sequence of integers starting from 'from' up to the length of vector 'x'. ```APIDOC ## Function: seq2_along ### Description Generates an integer sequence starting from 'from' and ending at the length of the provided vector 'x'. ### Arguments - **from**: The starting point of the sequence. - **x**: A vector whose length determines the end point of the sequence. ### Value An integer vector containing a strictly increasing sequence. ### Examples ```r seq2_along(10, letters) ``` ``` -------------------------------- ### List search names and environments Source: https://rlang.r-lib.org/reference/search_envs Use `search()` to list the names of environments on the search path, and `search_envs()` to retrieve the actual environment objects. ```r search() #> [1] ".GlobalEnv" "package:rlang" "package:stats" #> [4] "package:graphics" "package:grDevices" "package:utils" #> [7] "package:datasets" "package:methods" "Autoloads" #> [10] "package:base" ``` ```r search_envs() #> [[1]] $ #> [[2]] $ #> [[3]] $ #> [[4]] $ #> [[5]] $ #> [[6]] $ #> [[7]] $ #> [[8]] $ #> [[9]] $ #> [[10]] $ ``` -------------------------------- ### as_data_mask Source: https://rlang.r-lib.org/reference/as_data_mask Transforms a list or data frame to a data mask, automatically installing the .data pronoun. ```APIDOC ## as_data_mask ### Description Transforms a list or data frame to a data mask. It automatically installs the data pronoun `.data`. ### Usage as_data_mask(data) ### Arguments - data: A data frame or named vector of masking data. ### Value A data mask that you can supply to [`eval_tidy()`](https://rlang.r-lib.org/reference/eval_tidy.md). ### Details Unlike [`base::eval()`](https://rdrr.io/r/base/eval.html) which takes any kind of environments as data mask, [`eval_tidy()`](https://rlang.r-lib.org/reference/eval_tidy.md) has specific requirements in order to support [quosures](https://rlang.r-lib.org/reference/topic-defuse.md). For this reason you can't supply bare environments. `as_data_mask()` transforms a list or data frame to a data mask. It automatically installs the data pronoun [`.data`](https://rlang.r-lib.org/reference/dot-data.md). Once you have built a data mask, simply pass it to [`eval_tidy()`](https://rlang.r-lib.org/reference/eval_tidy.md) as the `data` argument. You can repeat this as many times as needed. Note that any objects created there (perhaps because of a call to `<-`) will persist in subsequent evaluations. ``` -------------------------------- ### Usage of local_bindings and with_bindings Source: https://rlang.r-lib.org/reference/local_bindings Illustrates the function signatures for `local_bindings()` and `with_bindings()`. `local_bindings()` takes name-value pairs and an optional environment or frame. `with_bindings()` takes an expression and name-value pairs, defaulting to the caller environment. ```r local_bindings(..., .env = .frame, .frame = caller_env()) ``` ```r with_bindings(.expr, ..., .env = caller_env()) ``` -------------------------------- ### Inject names using glue syntax Source: https://rlang.r-lib.org/reference/dyn-dots Demonstrates injecting argument names using glue syntax on the left-hand side of `:=`. This allows for dynamically constructed argument names. ```r if (is_installed("glue")) { nm <- "key" f("{nm}" := "value") f("prefix_{nm}" := "value") } ``` -------------------------------- ### Example: Check decimal number Source: https://rlang.r-lib.org/reference/check_type_number Demonstrates successful validation of a decimal number and catching an error when a string is provided. ```r check_number_decimal(3.14) try(check_number_decimal("x")) #> Error in eval(expr, envir) : #> `"x"` must be a number, not the string "x". ``` -------------------------------- ### Providing a default value with env_get Source: https://rlang.r-lib.org/reference/env_get Shows how to use `env_get()` to retrieve an object, providing a default value that is returned if the object is not found. This prevents an error when the binding does not exist. ```r # You can also avoid an error by supplying a default value: env_get(env, "foo", default = "FOO") #> [1] "FOO" ``` -------------------------------- ### Evaluating expressions with `expr()` and `eval()` Source: https://rlang.r-lib.org/reference/topic-data-mask.html Illustrates how to create an expression using `expr()` and then evaluate it. ```R expr(1 + 1) #> 1 + 1 eval(expr(1 + 1)) #> [1] 2 ``` -------------------------------- ### Example usage of check_string Source: https://rlang.r-lib.org/reference/check_type_scalar Shows the correct usage of `check_string()` with a string input and how it generates an error for a numeric input. ```r check_string("hello") try(check_string(42)) ``` -------------------------------- ### Get the number of symbols bound in an environment Source: https://rlang.r-lib.org/reference/env_names Use `env_length()` to determine the total number of bindings within a given environment. ```r env_length(env) ``` -------------------------------- ### Trace backtrace with custom top environment Source: https://rlang.r-lib.org/reference/trace_back Demonstrates how to set a custom top environment for backtraces, useful for trimming irrelevant contexts like knitr evaluation. This improves the clarity of backtraces in documentation and reports. ```r # Trim backtraces automatically (this improves the generated # documentation for the rlang website and the same trick can be # useful within knitr documents): options(rlang_trace_top_env = current_env()) f <- function() g() g <- function() h() h <- function() trace_back() # When no lazy evaluation is involved the backtrace is linear # (i.e. every call has only one child) f() ``` ```r # Lazy evaluation introduces a tree like structure identity(identity(f())) ``` ```r identity(try(f())) ``` ```r try(identity(f())) ``` ```r # When printing, you can request to simplify this tree to only show # the direct sequence of calls that lead to `trace_back()` x <- try(identity(f())) x print(x, simplify = "branch") ``` ```r # With a little cunning you can also use it to capture the # tree from within a base NSE function x <- NULL with(mtcars, {x <<- f(); 10}) x ``` ```r # Restore default top env for next example options(rlang_trace_top_env = NULL) # When code is executed indirectly, i.e. via source or within an # RMarkdown document, you'll tend to get a lot of guff at the beginning ``` -------------------------------- ### Example: Check whole number Source: https://rlang.r-lib.org/reference/check_type_number Demonstrates successful validation of a whole number and catching an error when a non-whole number is provided. ```r check_number_whole(42) try(check_number_whole(3.5)) #> Error in eval(expr, envir) : #> `3.5` must be a whole number, not the number 3.5. ``` -------------------------------- ### Basic usage of set_names() Source: https://rlang.r-lib.org/reference/set_names Demonstrates setting names for a numeric vector using character vectors and the letters sequence. ```r set_names(1:4, c("a", "b", "c", "d")) ``` ```r set_names(1:4, letters[1:4]) ``` ```r set_names(1:4, "a", "b", "c", "d") ``` -------------------------------- ### Get the number of frames in a backtrace Source: https://rlang.r-lib.org/reference/trace_back Returns the number of frames in a given backtrace object. This is useful for understanding the depth of the call stack. ```r trace_length(trace) ``` -------------------------------- ### Convert symbols to strings with as_string() Source: https://rlang.r-lib.org/reference/as_string Demonstrates how as_string() converts R symbols into character strings and verifies the type change. ```r # Let's create some symbols: foo <- quote(foo) bar <- sym("bar") # as_string() converts symbols to strings: foo #> foo as_string(foo) #> [1] "foo" typeof(bar) #> [1] "symbol" typeof(as_string(bar)) #> [1] "character" ``` -------------------------------- ### Call function with formula and data using exec Source: https://rlang.r-lib.org/reference/exec Shows how to use exec() to call a function like lm() with a formula and data. Note that exec() may not generate the most readable call representation for certain inputs like formulas. ```r f <- disp ~ cyl exec("lm", f, data = mtcars) #> #> Call: #> lm(formula = .Primitive("quote")(disp ~ cyl), data = structure(list( #> mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, #> 19.2, 17.8, 16.4, 17.3, 15.2, 10.4, 10.4, 14.7, 32.4, 30.4, #> 33.9, 21.5, 15.5, 15.2, 13.3, 19.2, 27.3, 26, 30.4, 15.8, #> 19.7, 15, 21.4), cyl = c(6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, #> 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8, 4, 4, 4, 8, 6, #> 8, 4), disp = c(160, 160, 108, 258, 360, 225, 360, 146.7, #> 140.8, 167.6, 167.6, 275.8, 275.8, 275.8, 472, 460, 440, #> 78.7, 75.7, 71.1, 120.1, 318, 304, 350, 400, 79, 120.3, 95.1, #> 351, 145, 301, 121), hp = c(110, 110, 93, 110, 175, 105, #> 245, 62, 95, 123, 123, 180, 180, 180, 205, 215, 230, 66, #> 52, 65, 97, 150, 150, 245, 175, 66, 91, 113, 264, 175, 335, #> 109), drat = c(3.9, 3.9, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, #> 3.92, 3.92, 3.92, 3.07, 3.07, 3.07, 2.93, 3, 3.23, 4.08, #> 4.93, 4.22, 3.7, 2.76, 3.15, 3.73, 3.08, 4.08, 4.43, 3.77, #> 4.22, 3.62, 3.54, 4.11), wt = c(2.62, 2.875, 2.32, 3.215, #> 3.44, 3.46, 3.57, 3.19, 3.15, 3.44, 3.44, 4.07, 3.73, 3.78, #> 5.25, 5.424, 5.345, 2.2, 1.615, 1.835, 2.465, 3.52, 3.435, #> 3.84, 3.845, 1.935, 2.14, 1.513, 3.17, 2.77, 3.57, 2.78), #> qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, #> 20, 22.9, 18.3, 18.9, 17.4, 17.6, 18, 17.98, 17.82, 17.42, #> 19.47, 18.52, 19.9, 20.01, 16.87, 17.3, 15.41, 17.05, 18.9, #> 16.7, 16.9, 14.5, 15.5, 14.6, 18.6), vs = c(0, 0, 1, 1, 0, #> 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, #> 0, 1, 0, 1, 0, 0, 0, 1), am = c(1, 1, 1, 0, 0, 0, 0, 0, 0, #> 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, #> 1, 1, 1, 1), gear = c(4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, #> 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, #> 4), carb = c(4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, #> 4, 4, 1, 2, 1, 1, 2, 2, 4, 2, 1, 2, 2, 4, 6, 8, 2)), row.names = c("Mazda RX4", #> "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", #> "Valiant", "Duster 360", "Merc 240D", "Merc 230", "Merc 280", #> "Merc 280C", "Merc 450SE", "Merc 450SL", "Merc 450SLC", "Cadillac Fleetwood", #> "Lincoln Continental", "Chrysler Imperial", "Fiat 128", "Honda Civic", #> "Toyota Corolla", "Toyota Corona", "Dodge Challenger", "AMC Javelin", #> "Camaro Z28", "Pontiac Firebird", "Fiat X1-9", "Porsche 914-2", #> "Lotus Europa", "Ford Pantera L", "Ferrari Dino", "Maserati Bora", #> "Volvo 142E"), class = "data.frame")) #> #> Coefficients: #> (Intercept) cyl #> -156.6 62.6 #> ``` -------------------------------- ### Compare byte sizes Source: https://rlang.r-lib.org/reference/bytes-class Bytes vectors created with `parse_bytes()` can be directly compared numerically. This example shows that '1KB' is less than '1MB'. ```r parse_bytes("1KB") < "1MB" #> [1] TRUE ```