A collection of Universally Useful functions!
Installation
You can install the development version of UU from GitHub with:
# install.packages("devtools")
devtools::install_github("yogat3ch/UU")
Check out the pkgdown site for more details!
All the fun(s)!
Name | Concept | Title | Description |
---|---|---|---|
character_codes | Replace HTML Character codes with their character equivalent | See ?.character_codes for conversion table. Note that this will not translate Ampersand if converting from Namedcode to character because it will translate the Namedcodes themselves. | |
col_type_hash | Index of column type conversions | ||
color_interpolate | Interpolate between two colors | ||
common_names | Find the common names between two objects | Given named objects, find the names in common | |
concat_rows | Concatenate row values in a poorly scraped table | ||
create_simple_get_function | Create a function that creates an object and assigns it to a namespace the first time it’s called and subsequently retrieves it from the namespace thereafter. | Useful when the object depends on a long running task such as a database query. | |
css_col2vec_ | Vectorized version of css_col2vec | ||
.character_codes | Character code conversion table | ||
.time_factor | Timespans as factor | ||
expr_pipe | Return a list of expressions all piped together as a single expression | Useful when making complex compound statements that require dynamic substitution via tidy eval for dynamically created variables derived from the context. | |
file_timestamp | Make a file path compliant ISO8601 timestamp | ||
filter_to | Change or apply filters to output type | Useful in concert with axis brushing | |
find_by_class | Find an object by it’s class | ||
fml_list | Print function formals as a list | ||
fn_name | Retrieve the function name | Sometimes a function is passed down the call stack and it’s name is unknown. This function finds the name without having to pass it down the call stack as an argument. | |
formula_make | Create a formula given predictors and a label (response variable) | ||
increment | Increment an in-place counter | ||
join_check | Detect possible duplicates of rows or columns after a join | ||
json_validate | Is JSON file or text valid? | ||
key_out | Handle different output type requests for match_df | ||
list_rename | Rename a list | From https://stackoverflow.com/users/6646912/krassowskikrassowski on SO https://stackoverflow.com/a/73621060/2675597link | |
map_class | Match the classes of one object to that of another object | ||
match_df | Extract matching rows of a data frame. | Match works in the same way as join, but instead of return the combined dataset, it only returns the matching rows from the first dataset. This is particularly useful when you’ve summarised the data in some way and want to subset the original data by a characteristic of the subset. | |
match_letters | Match the first n letters to supplied arguments | Case insensitive matching of argument to possibilities provided in ellipsis. | |
meeting_timer | Partition a meeting into evenly distributed sections based on how much time is left between when intros end and the end of the meeting | ||
missing_args | Get the missing arguments from the function as character | ||
nonull | Is value non-null? | ||
not_na | Is value non-NA? | ||
object_ext | Provide the appropriate file extension for a given object | ||
reexports | Objects exported from other packages | These objects are imported from other packages. Follow the links below to see their documentation. plyrround_any rlang%||% | |
regex_op | Create a compound regex grouped statement | ||
regex_or | Create a compound regex grouped OR statement | ||
startup | Load project & user-level .Renviron & .Rprofile | ||
unit_conversion | Abbreviations of numeric magnitude for various units | ||
unit_shorthand | Easily translate long form unit names to shorthand | Useful for condensed displays like axis titles | |
was_updated | Was a file updated in the last hour? | ||
week_bins_per_year | Create a tbl with each day of the year, it’s week number, and the interval containing that week. | ||
which_cols | Translate DT Column names to numeric indices using regex matching | ||
color_cycle | color | Makes a cyclic color palette of a specified length using the specified transformation each cycle | |
color_distance | color | Compute color distance | |
color_luminance | color | Find the luminance of a particular color, scaled 0-1 | |
color_match | color | Match colors by visual distance | Helpful for pairing colors across light/dark palettes |
color_rgb_table | color | Convert vector of colors to named tbl | |
color_separate | color | Separate a vector of colors based on their distance | |
color_text_by_luminance | color | Set text color based on luminance | Useful for applying one or another of text colors based on the luminance of a background |
colors2css | color | Convert a list of colors to SCSS/Sass variables or classes | |
css_col2vec | color | Convert a CSS representation of a color to an r,g,b numeric | |
luminance_filter | color | Filter colors based on a luminance threshold | |
rgb2hex | color | Convert r,g,b,a values as string or numeric to hex | |
gbort | condition signaling | Custom error message | Throw abort with format_error |
ginfo | condition signaling | Custom info message | Provide info with inform |
gmsg | condition signaling | Custom message Message using format_message & cat_line | |
gwarn | condition signaling | Custom warning message | Throw cli_alert_warning with format_warning |
trace_back_json | condition signaling | Writes a trace back as a json for error logging Useful for remote error logging on deployed shiny apps, such as via Sentry | |
is_error | conditionals | Is object an error | |
is_legit | conditionals | Is object legit? | Is object non-null, non-empty, non-NA, and not a try-error? |
is_project | conditionals | Is Session in a Project? | |
larger | conditionals | Which is larger | |
most | conditionals | Are most values TRUE | IF more than half the values are TRUE, returns TRUE |
same | conditionals | Are the values in each object the same? | The primary difference from identical & all.equal is that objects are sorted by name so order doesn’t matter. Set sort_by_names = FALSE to sort by values. |
zchar | conditionals | Is zero-length character? | |
col_types | file IO | Converts input to a specified type output | Given various inputs, provide a col_type specification in the format indicated by outtype |
dep_read | file IO | Read a dependency from file | |
dep_write | file IO | Write a dependency to file | |
dir_fn | file IO | Create a directory path pointing function | |
dirs | file IO | Path functions for commonly used directories | |
ext | file IO | Extract the file extensions from a filepath | Given a path, extract the file extension |
file_fn | file IO | Return the appropriate function for reading the specified path/extension | |
is_filepath | file IO | Is path a file path | Given a path, is it a filepath? |
last_updated | file IO | Gather last updated times for on-disk files | Check the last modified time files or paths |
list.files2 | file IO | List full file paths with the file name as the name | |
load_obj | file IO | Load an R object from a file | This function loads an R object from a file into the global environment or a new environment. |
make_names | file IO | Make a file path name with underscores | |
mkpath | file IO | Construct a path | Given a path, construct it if it does not exist. |
move_files_to_folder | file IO | Move all files to a folder | |
needs_update | file IO | Check if files need to be updated | |
object_fn | file IO | Return the appropriate function for writing the supplied object to disk | |
object_write | file IO | Provide the appropriate file read/write function | Write an object to disk |
package_size | file IO | Return the size of a package, or all packages in a folder | |
write_dir_fn | file IO | Write dir helper function that are robust to dev vs deployed package states | |
write_lines | file IO | Write lines at a specific location in a file | |
.file | file navigation | All the files that can be navigated to with file if they exist | |
file | file navigation | Go to a specified file | A List object with convenience functions that open the named file in RStudio. An R named sublist of all files in the R folder if such a folder exists |
folder | file navigation | Go to a specified folder | |
%allin% | infixes | Are all lhs values in rhs? | |
%nin% | infixes | Are lhs values absent from set on rhs? | |
%|0|% | infixes | Replace a 0 length value | If the lhs is length 0, replace with rhs |
%|% | infixes | Replace NA values in LHS with RHS | Does not strictly enforce class typing like op-na-default |
%|legit|% | infixes | If legit lhs, else rhs | |
%|try|% | infixes | Try an expression | Calls the expression (LHS) & if it fails return RHS |
%|zchar|% | infixes | Replace zero-length character strings with right hand side | |
comparison_inverse_key | math | Math comparison comparator inverse key | |
comparison_inverse | math | Convert a math comparator to it’s inverse | |
comparison_key | math | Math comparison comparator to plain english key | |
evens | math | Get even numbers | |
interpolate | math | Simple interpolate between two numbers | |
odds | math | Get odd numbers | |
str_comparison | math | Convert inequality statements between character, mathematic, symbol and function representations | |
assign_global | namespaces | Assign an object to the global environment | |
assign_in_ns | namespaces | Assign a variable into a namespace | Unlocks and relocks namespaces and bindings as needed |
get_from_ns | namespaces | Get an object from a namespace | |
get_global | namespaces | Get an object from the global environment | |
pkg_ns | namespaces | Return the current package namespace | |
unload_namespaces | namespaces | Unload namespaces prior to package install | |
if_debug | options | Run expressions only when option use_debug = TRUE | |
opts | options | Check option value. | This is a list that will populate dynamically with the options in the project local .Rprofile allowing them to be read by calling the method. This population of methods happens at the beginning of a session. It can be accessed with UU::opts. If you wish to check option values in non-interactive sessions, see the write_opts function which will write a file with an opts object based on the current state of .Rprofile that can be used during non-interactive (deployed apps) sessions. |
toggle | options | Toggle or change an option listed in a local .Rprofile for the session | Any options in the project local .Rprofile will populate this object as named methods. These named methods, when called, will toggle the options on or off. Alternatively, if an option is not logical, it can be changed using the set argument. This loads at the start of an R session if startup has been called in the user-level .Rprofile. These methods are meant for interactive use only. |
write_opts | options | Write all the option checking functions to a file | |
get_package_fns | package dev | Get the names of all exported functions in a package | |
is_package_dev | package dev | Is package in development or installed | |
is_package | package dev | Is working directory a package? | |
need_pkg | package dev | Get a function from a package, abort if package not installed. | |
pkg_chr_split_comma | package dev | Split a list of packages separated by commas | |
profile_script | profiling | profile_script | This function will add profiling code to a script wherever the following flags are found in the first non-spacing characters on the line: #<p Opening comment flag where profile_open will be inserted. #>p Closing comment flag where profile_close will be inserted. |
creds_to_renviron | project setup | Write named keypairs to an .Renviron / .Rprofile file | Writes key pairs to .Renviron / .Rprofile and adds .Renviron to .gitignore if not already there. |
fun_docs_table | project setup | Create a table of functions and their uses | |
ignore_files | project setup | Add lines to .gitignore | |
install_remote | project setup | Install a package | |
key_pairs_duplicated | project setup | Find duplicates in key pairs | |
key_pairs_text | project setup | Make key-pairs from a named character vector | |
use_reimport | project setup | Add a function to reimports | |
use_UU_reimports | project setup | Write R/aaa_reimports.R file with all current infix operators | All infix operators available: %allin%, %nin%, %|%, %|0|%, %|legit|%, %|try|%, %|zchar|%, and %||% |
write_to_rprofile | project setup | Write expressions to the .Rprofile | |
magnitude_order | rounding | Compute the order of magnitude | Uses the floor to round |
magnitude_triplet | rounding | Compute the order of magnitude triplet ie thousand, million, trillion | |
num_chr_suffi | rounding | Abbreviations of numeric magnitude | |
num2str_vec | rounding | Convert number to string Vectorized version | |
num2str | rounding | Convert numeric value to a string abbreviation with K, M, B for Thousand, Million & Billion | |
round_to | rounding | Find convenient limits of input vectors | If accuracy is omitted, number will be rounded to the nearest order of magnitude IE 145, if fn = min, will round to 100 |
size | rounding | Digital storage size conversion See object.size | Digital storage size conversion See object.size Vectorized version of size |
unit_find | rounding | Find the row corresponding to a value in unit_conversion | |
unit_modify_vec | rounding | Modify unit abbreviation, vectorized version | |
unit_modify | rounding | Modify unit abbreviations | |
unit_string | rounding | Extract the units from a string | It is assumed that units are encased in parentheses at the end of the string |
as_js | shiny | Preserve a string as JS/HTML (prevent translation of characters) | |
glue_js | shiny | Create a JS string with glue insertions glue .open = !@ & .close = @# | |
nm_to_id | shiny | Make a randomly formatted name into snakecase id | |
path_strip_shiny | shiny | Strip a file path to everything after resourcepath if shiny is running | Useful for linking to internal files, such as with image source attributes <img src=“[path]”> |
path_strip_to | shiny | Strip a file path to everything after resourcepath | Useful for linking to internal files, such as with image source attributes <img src=“[path]”> |
read_js | shiny | Read Javascript file | |
shiny_error_recover | shiny | Toggle recover on error when obtuse shiny errors are encountered | |
strip_html | shiny | Remove all HTML tags from a character vector | |
max2 | statistics | An alternative to max that preserves names | |
smode | statistics | Statistical mode | Return the most frequenctly occuring item in a dataset |
duration_print | time | Translate a duration into the human-legible estimation as a character | |
excel_date | time | Convert Excel character date representation to a Date | |
month_factor | time | Month as factor/numeric | |
season_factor | time | Season as factor/numeric | |
time_aggregates | time | Timespans as character | |
time_difftimes | time | Timespans as durations | |
time_elapsed | time | Return a logical on an interval | |
time_factor | time | Turn timespans into an ordered factor | |
timespan | time | Create a timespan duration | |
week_factor | time | Day of the week as factor/numeric | |
len_unique | vectors | The length of unique values in a vector | |
names_values_switch | vectors | Switch the names and the values of a vector | |
rle_df | vectors | rle_df - create a run-length-encoding data.frame | Given an rle this function will return a data.frame of starts, ends, and indexes thereof of the run lengths. Credit: https://stackoverflow.com/questions/43875716/find-start-and-end-positions-indices-of-runs-consecutive-values |
rle_groups | vectors | Create an RLE Grouping from a logical vector | |
rle_seq | vectors | Create a sequence from the start to the end for a given value from an rle_df for indexing | |
sort_by_names | vectors | Sort a vector or list by it’s name (or self if no names) | |
true_names | vectors | Return the names of all TRUE items in a logical vector | |
unify_vec_preserve_order | vectors | Unify two vectors preserving the order of x | |
unique_with_names | vectors | Unique a vector, preserving the names of the first original entries | |
vlookup_from_ref | vectors | Vlookup replace using a lookup column and reference table | |
zchar_remove | vectors | Remove zero length strings (or string with all spaces) | |
xpath_sibling_between | webscraping | Generate xpath to find sibling nodes between two elements The function produces a compounding xpath with each subsequent argument provided. Thus the final argument specified will be the node that is selected by the resulting xpath with the exception of nested_tag_contains which helps to identify a nested tag by its contents |