Title: | Various functions for personal use |
---|---|
Description: | Various functions for personal use. |
Authors: | Vencislav Popov [aut, cre] |
Maintainer: | Vencislav Popov <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.1.10 |
Built: | 2024-11-12 03:55:11 UTC |
Source: | https://github.com/venpopov/Vmisc |
Equivalent to python's string concatenation via + operator
a %+% b
a %+% b
a |
an R object to be converted to a character vector. |
b |
an R object to be converted to a character vector. |
String concatenation of a and b
# adding a string and a vector "name" %+% 1:10 # adding vector variables and strings names <- c("John", "Sarah") ages <- c(34,23) res <- names %+% " is " %+% ages %+% " years old" identical(res, c("John is 34 years old", "Sarah is 23 years old"))
# adding a string and a vector "name" %+% 1:10 # adding vector variables and strings names <- c("John", "Sarah") ages <- c(34,23) res <- names %+% " is " %+% ages %+% " years old" identical(res, c("John is 34 years old", "Sarah is 23 years old"))
This function takes any number of R language objects and converts their names into strings.
This is particularly useful for programming where variable names or symbols need to be used
as strings without evaluating them. It leverages rlang
's tidy evaluation framework.
arg2string(...)
arg2string(...)
... |
Arbitrary arguments representing R language objects or symbols. |
A character vector where each element is the string representation of the corresponding argument passed to the function. The order of the strings in the output matches the order of the arguments.
# returns the arguments as strings even though functions bmm() and brms() are not defined arg2string(bmm('0.4.0'), brms('2.20.4'))
# returns the arguments as strings even though functions bmm() and brms() are not defined arg2string(bmm('0.4.0'), brms('2.20.4'))
An infix operator to get the attribute of an object (equivalent to attr(x, "name", exact = TRUE))
x%a%which x%a%which <- value x%A%which x%A%which <- value
x%a%which x%a%which <- value x%A%which x%A%which <- value
x |
an object whose attributes are to be accessed. |
which |
a non-empty character string specifying which attribute is to be accessed. |
value |
an object, the new value of the attribute, or |
These functions provide access to a single attribute of an object. The replacement form causes the named attribute to take the value specified (or create a new attribute with the value given).
For the extractor, the value of the attribute matched, or NULL
if no exact match is found and no or more than one partial match is found.
x <- 1 attr(x, "name") <- "John" x%a%name x%A%name x%a%name <- "Alice" attr(x, "name") x <- 1:10 x%A%dim <- c(2,5) x
x <- 1 attr(x, "name") <- "John" x%a%name x%A%name x%a%name <- "Alice" attr(x, "name") x <- 1:10 x%A%dim <- c(2,5) x
A character vector of available packages in the library
available_packages(path = .libPaths())
available_packages(path = .libPaths())
path |
A character vector of paths to search for the package. Default is the default library paths. |
A character vector of available package names in the library. If any package versions were installed via pkg_vload(), the version will be shown as "pkg-version"
Wrapper around paste
with collapse
argument set to ""
. This results in
a single string.
collapse(..., sep = "")
collapse(..., sep = "")
... |
one or more R objects, to be converted to character vectors and concatenated. |
sep |
a character string to separate the terms. |
A single string.
x <- 1:10 res <- collapse(x) identical(res, '12345678910')
x <- 1:10 res <- collapse(x) identical(res, '12345678910')
Report Space Allocated for the Components of a List
component_size(x, units = "auto")
component_size(x, units = "auto")
x |
A list object |
units |
A string specifying the units to use for the size. Default is "auto". |
A list with the same names as the input list, where each element is the size
x <- list(a = 1:10, b = 1:100) component_size(x)
x <- list(a = 1:10, b = 1:100) component_size(x)
Given a function name and a package, this function will extract all calls to the said function from the package. The function can be any function name, either imported or defined in the package.
extract_pkg_fun_calls(pkg, fun)
extract_pkg_fun_calls(pkg, fun)
pkg |
Name of the package from which to extract function calls |
fun |
Name of the function to extract calls to |
A character vector with the extracted function calls. Each value is of the form "fun(arg1=value1, arg2=value2, ...)"
extract_pkg_fun_calls("utils", "getOption")
extract_pkg_fun_calls("utils", "getOption")
This function checks whether one or more directories are empty. An empty directory is one that contains no files or subdirectories. If the directory does not exist, it is considered as empty.
is_dir_empty(paths)
is_dir_empty(paths)
paths |
A character vector containing one or more file paths. Each path is checked to determine if the corresponding directory is empty. |
A logical vector where each element corresponds to a directory
specified in paths
. TRUE
indicates that the directory is empty,
and FALSE
indicates that it is not.
## Not run: # Create two temporary directories one of which is empty library(fs) dir1 <- tempfile() dir2 <- tempfile() dir_create(c(dir1, dir2)) dir_create(file.path(dir1, "subdir")) # Check if the directories are empty (should return FALSE, TRUE) is_dir_empty(c(dir1, dir2)) # Clean up dir_delete(c(dir1, dir2)) ## End(Not run)
## Not run: # Create two temporary directories one of which is empty library(fs) dir1 <- tempfile() dir2 <- tempfile() dir_create(c(dir1, dir2)) dir_create(file.path(dir1, "subdir")) # Check if the directories are empty (should return FALSE, TRUE) is_dir_empty(c(dir1, dir2)) # Clean up dir_delete(c(dir1, dir2)) ## End(Not run)
This function creates a named list from its arguments. If the arguments are named, those names are used in the resulting list. If some arguments are unnamed, the variable names themselves are used as names in the list. This can be useful for creating lists where the names are important for later indexing or manipulation, and ensures all elements in the list have names.
nlist(...)
nlist(...)
... |
Arbitrary arguments to be included in the list. These can be named or unnamed. Unnamed arguments will be named based on their variable names. |
A list where each element corresponds to an argument passed to the function. Elements of the list are named based on either their original names or the names of the variables passed as arguments.
var1 <- 1 var2 <- 1:10 # This will return a list with names: c("a", "b", "var1", "var2") nlist(a = 1, b = 2, var1, var2)
var1 <- 1 var2 <- 1:10 # This will return a list with names: c("a", "b", "var1", "var2") nlist(a = 1, b = 2, var1, var2)
NULL
This infix function makes it easy to replace NULL
s with a default
value. It's inspired by the way that Ruby's or operation (||
)
works.
x %||% y
x %||% y
x , y
|
If |
1 %||% 2 NULL %||% 2
1 %||% 2 NULL %||% 2
packageOptions()
scrapes the source code of a package to find all calls to
getOption()
and returns a tidied list of the current values of the options.
Initial running time might be slow if a package contains a large amount of
code. Repeated calls to the function will be significantly faster.
packageOptions(pkg, own_only = FALSE, max_length = 50, show_defaults = FALSE)
packageOptions(pkg, own_only = FALSE, max_length = 50, show_defaults = FALSE)
pkg |
Name of the package to extract options from |
own_only |
Logical. If |
max_length |
Integer. Controls the maximum length of individual the default values to be printed. You will rarely need to change this. However, if your results include strange output with very long strings defining default values via internal functions, you can decrease this value to suppress them. Default is 50. |
show_defaults |
Logical. If |
A named list of the current values of the options. This list can be saved to a variable and used with option() to restore the options to these values at a later time should you change them.
packageOptions("utils")
packageOptions("utils")
Parse package name and version from a pkg('verions') call
parse_pkg_version(...)
parse_pkg_version(...)
... |
a number of calls to objects of type pkg('version') where pkg is the package name and version is the version number |
A list with two elements: names and versions. The names are the package names and the versions are of class 'package_version'. If the version is not specified, the version will be NA.
parse_pkg_version(brms("2.20.4"), bmm("0.4-0"), utils)
parse_pkg_version(brms("2.20.4"), bmm("0.4-0"), utils)
pkg_switch_default()
renames the folder of the default version of a package
to pkg-version and renames the folder of the new default version to pkg. This
allows the user to switch between different versions of the same package that
are loaded by the default call to library()
.
pkg_switch_default(pkg, new_default_version, path = .libPaths())
pkg_switch_default(pkg, new_default_version, path = .libPaths())
pkg |
The name of the package |
new_default_version |
The version of the package to be set as the default |
path |
A character vector of paths to search for the package. Default is the default library paths. |
Invisible TRUE
if the default version was successfully switched, FALSE
otherwise.
## Not run: # install two versions of the xfun package pkg_vload(stringr, stringr('1.0.0')) # switch the default version of xfun to 0.2.0 pkg_switch_default("stringr", "1.0.0") ## End(Not run)
## Not run: # install two versions of the xfun package pkg_vload(stringr, stringr('1.0.0')) # switch the default version of xfun to 0.2.0 pkg_switch_default("stringr", "1.0.0") ## End(Not run)
pkg_vavailable()
is an alternative to xfun::pkg_available()
that checks
for a specific version of the package rather than a minimal version. If the
version is not specified, the function will check for the default version of
the package.
pkg_vavailable(..., path = .libPaths(), exact = TRUE)
pkg_vavailable(..., path = .libPaths(), exact = TRUE)
... |
One or more calls to the package name with version (if desired) specified in parantheses. E.g. brms("2.14.4") or brms or "brms" |
path |
A character vector of paths to search for the package. Default is the default library paths. |
exact |
Logical. If |
To check for a specific version, the function assumes that this version was installed using pkg_load(pkg(version)), which has created a folder named "pkg-version" in the library.
a named list with the following elements:
available: A logical vector indicating whether the package is available
pkg_name: The name of the package
pkg_version: The version of the package in the library
pkg_version_specified: The version of the package specified in the call to pkg('version')
pkg_folder: The folder name of the package in the library
## Not run: pkg_vavailable(utils) pkg_vavailable(xfun("0.1.0")) pkg_vavailable(utils, brms("2.14.4"), xfun("0.1.0")) # compare with xfun::pkg_available() xfun::pkg_available("xfun", "0.1.0") # returns TRUE ## End(Not run)
## Not run: pkg_vavailable(utils) pkg_vavailable(xfun("0.1.0")) pkg_vavailable(utils, brms("2.14.4"), xfun("0.1.0")) # compare with xfun::pkg_available() xfun::pkg_available("xfun", "0.1.0") # returns TRUE ## End(Not run)
pkg_vload() attempts to load a package and, if it is not available, installs it. It can also install a specific version of a package. If the package is already installed, it will check if the version is the same as the one specified in the call. If the version is different, it will attempt to unload the package and install the specified version in a separate library, allowing the user to have multiple versions of the same package installed at the same time.
pkg_vload( ..., reload = FALSE, path = .libPaths(), repos = getOption("repos"), install_args = NULL )
pkg_vload( ..., reload = FALSE, path = .libPaths(), repos = getOption("repos"), install_args = NULL )
... |
One or more calls to the package name with version (if desired).
The calls should be of the form |
reload |
Logical. If |
path |
A character vector of paths to search for the package. Default is the default library paths. |
repos |
A character vector of repository URLs to use for installing the
package. Default is the value of |
install_args |
A list of additional arguments to be passed to
|
This function does not return a value. Instead, it will stop the execution and display a message if the requirements are not met.
## Not run: # Load the 'brms' package and install version 2.0.0 if it is not available pkg_vload(brms("2.0.0")) # Load multiple packages and install specific versions if they are not available pkg_vload(brms("2.0.0"), utils) ## End(Not run)
## Not run: # Load the 'brms' package and install version 2.0.0 if it is not available pkg_vload(brms("2.0.0")) # Load multiple packages and install specific versions if they are not available pkg_vload(brms("2.0.0"), utils) ## End(Not run)
This function checks if the required R packages are available and if their versions meet the specified minimum requirements. It will stop the execution and display a message if any required package is missing or does not meet the version requirement.
require_pkg(..., message_prefix = "Please install the following packages:")
require_pkg(..., message_prefix = "Please install the following packages:")
... |
Variable arguments representing required package names and,
optionally, their minimum versions. The versions should be specified
immediately after the package names, in the format |
message_prefix |
A character string to be displayed before the message if the requirements are not met. |
This function does not return a value. Instead, it will stop the execution and display a message if the requirements are not met.
## Not run: # Check if 'dplyr' and 'ggplot2' are installed (any versions): require_pkg(dplyr, ggplot2) # Check if 'dplyr' (version 1.0.0 or higher) and 'ggplot2' (version 8.3.0 or higher) are installed: require_pkg(dplyr('1.0.0'), ggplot2('8.3.0')) ## End(Not run)
## Not run: # Check if 'dplyr' and 'ggplot2' are installed (any versions): require_pkg(dplyr, ggplot2) # Check if 'dplyr' (version 1.0.0 or higher) and 'ggplot2' (version 8.3.0 or higher) are installed: require_pkg(dplyr('1.0.0'), ggplot2('8.3.0')) ## End(Not run)
return_on_exit() can be called from within a parent function to set a return value when the parent function exits for whatever reason. This is useful when you want to specify a conditional return value even if a function exits abruptly.
return_on_exit(fun, ..., env = parent.frame())
return_on_exit(fun, ..., env = parent.frame())
fun |
Function to evaluate upon exit and return the result from the calling function |
... |
Arguments to pass to the function |
env |
Environment to evaluate the function in and to return from. The
function will have access to the variables in this environment and their
state at the time of the exit (not the time of the function call). If you
want to pass variable values at the time of the function call, use |
The result of the function call
## Not run: # function to evaluate on exit f <- function(y, ...) { dots <- list(...) if ("x" %in% names(dots)) { x <- dots$x } x + y } # calling function g <- function(...) { x <- 1 # current value of x; will not be used if it changes before g exists y <- 10 # value of y to pass to f, will be used as is # setup conditional return return_on_exit(f, y, ...) # do some work for (i in 1:1000000) { x <- i if (i == 100) stop("Error, but I will return something!") } # this will not be executed cat("This will not be printed") return("This will not be returned") } # calling g() will return 110 g() # calling g() with x as an argument will return 30 # because x is passed to f() via the dots argument g(x = 20) ## End(Not run)
## Not run: # function to evaluate on exit f <- function(y, ...) { dots <- list(...) if ("x" %in% names(dots)) { x <- dots$x } x + y } # calling function g <- function(...) { x <- 1 # current value of x; will not be used if it changes before g exists y <- 10 # value of y to pass to f, will be used as is # setup conditional return return_on_exit(f, y, ...) # do some work for (i in 1:1000000) { x <- i if (i == 100) stop("Error, but I will return something!") } # this will not be executed cat("This will not be printed") return("This will not be returned") } # calling g() will return 110 g() # calling g() with x as an argument will return 30 # because x is passed to f() via the dots argument g(x = 20) ## End(Not run)
stop
and warning
that do not print the call stackIn addition they allow to use glue
to create the error message
stop2(..., env.frame = -1) warning2(..., env.frame = -1)
stop2(..., env.frame = -1) warning2(..., env.frame = -1)
... |
zero or more objects which can be coerced to character (and which are pasted together with no separator) or a single condition object |
env.frame |
the environment to use for the error message if you use |
Stops execution and prints the error message
## Not run: stop2("This is an error message") x <- 1 stop2("This is an error message with a variable: {x}") ## End(Not run)
## Not run: stop2("This is an error message") x <- 1 stop2("This is an error message with a variable: {x}") ## End(Not run)
Wrapper around stopifnot allowing for a custom error message
stopifnot2(..., msg = NULL) stopif(..., msg) warnif(..., msg)
stopifnot2(..., msg = NULL) stopif(..., msg) warnif(..., msg)
... |
zero or more expressions to be evaluated |
msg |
a custom error message to be printed if the expressions are not all true |
Used to, for example, extract a function call from code, ignoring paranthesis within function arguments
str_extract_nested_balanced(string, prefix, opening = "(", closing = ")")
str_extract_nested_balanced(string, prefix, opening = "(", closing = ")")
string |
A character vector |
prefix |
A string to match at the beginning of the substring |
opening |
A character to match as the opening character |
closing |
A character to match as the closing character |
There will be a match only if the function is not used as text in
quotes immediately before the function call. For example, in the string
"something myFunction(x = 1, y = mean(x)) otherFunction()", the function
call to myFunction
will be matched, but the function call in the string
"var = \"myFunction(x = 1, y = mean(x))\"" or print("myFunction(x = 1, y =
mean(x))") will not. This ensures that we do not retrieve examples or
instructions about usage
A character vector with the extracted substring
x <- "something myFunction(x = 1, y = mean(x)) otherFunction()" str_extract_nested_balanced(x, "myFunction", "(", ")")
x <- "something myFunction(x = 1, y = mean(x)) otherFunction()" str_extract_nested_balanced(x, "myFunction", "(", ")")
Remove all attributes of an object except those specified as protected
strip_attributes(x, protect = c("names", "row.names", "class"))
strip_attributes(x, protect = c("names", "row.names", "class"))
x |
an R object |
protect |
a character vector of attribute names to keep. Default is
|
An R object with all attributes removed except those specified in
protect
.
x <- data.frame(a = 1:10, b = 11:20) attr(x, "remove_me") <- "I want to be removed" attributes(x) x <- strip_attributes(x, protect = c("names", "row.names", "class")) attributes(x)
x <- data.frame(a = 1:10, b = 11:20) attr(x, "remove_me") <- "I want to be removed" attributes(x) x <- strip_attributes(x, protect = c("names", "row.names", "class")) attributes(x)