Package 'jimstools'

Title: Tools for R
Description: What the package does (one paragraph).
Authors: Jimmy Briggs [aut, cre]
Maintainer: Jimmy Briggs <[email protected]>
License: MIT + file LICENSE
Version: 0.4.0
Built: 2024-11-23 03:03:35 UTC
Source: https://github.com/jimbrig/jimstools

Help Index


Aliases

Description

These simple aliases can be useful to avoid operator precedence ambiguity, or to make use of indents from commas within your text editor. The all-caps versions accept single-length (capable of 'short-circuits') logical conditions only.

Neithers and nors are identical except have slightly different short-circuits. NOR uses negation once so may be quicker if the first argument is very, very prompt.

Usage

AND(x, y)

OR(x, y)

nor(x, y)

neither(x, y)

NOR(x, y)

NEITHER(x, y)

pow()

XOR(x, y)

Arguments

x, y

Logical conditions.


Backup Raw Data

Description

This function copies raw data from an external location (i.e. a mapped network drive) to a specified local project directory. In addition, a snapshot of the files being copied is taken and stored in the specified "cache_dir" so that files are only re-copied if changed.

Usage

backup_raw(from_dir, to_dir, cache_dir = "cache", force = FALSE)

Arguments

from_dir

Directory to copy from.

to_dir

Directory to copy to.

cache_dir

Directory to store cached file snapshots.

force

Logical indicating if copying should be forced.

Value

Invisible - this function is used for its side effects


Create README badges via img.shields.io

Description

Create README badges via img.shields.io

Usage

badge(label, value, color, url)

Arguments

label

badge label

value

badge value

color

badge color

url

url

Value

character string to be pasted into README


Open fontawesome icons webpage

Description

Open fontawesome icons webpage

Usage

browse_fontawesome()

Caching Utility Functions

Description

Quick caching utility read/write functions utilizing the qs package.

Usage

write_cache(x, name = NULL, cache_dir = "cache", overwrite = TRUE)

read_cache(x, name = NULL, cache_dir = "cache")

Arguments

x

object to cache

name

name of object to read in.

cache_dir

path to cache directory.

overwrite

logical (default = TRUE)

Value

invisibly returns object passed to the function.

x

invisibly attaches object to parent global environment

See Also

qs::qread() and qs::qsave()

Examples

## Not run: 
mydata <- mtcars
write_cache(mydata) # will save to 'cache/mydata'.
write_cache(mydata, "mydata-v2", cache_dir = "data/temp") # will save to 'data/temp/mydata-v2'

# read back in
read_cache(mydata)

## End(Not run)

Coalesce Join

Description

Coalesce Join

Usage

coalesce_join(
  x,
  y,
  by = NULL,
  suffix = c(".x", ".y"),
  join = dplyr::full_join,
  ...
)

Arguments

x

data.frame

y

data.frame to join with

by

variables to join by

suffix

common variables suffix

join

type of join

...

passed to join function

Value

joined data.frame with values replaced


Collapse Rows

Description

for each group, sets the top row of the group to the group's value. All other rows in the group are set to "". See the example

Usage

collapseRows(df, variable)

Arguments

df

a data frame

variable

group variable to be collapsed

Value

a data frame with an updated variable column


Compare to Prior

Description

Compares data across evaluations.

Usage

compare_to_prior(data, col)

Arguments

data

current data

col

columns to compare (character vector)

Value

new data frame with added columns for changes and priors


Create Project

Description

Create Project

Usage

create_project(
  path,
  rstudio = rstudioapi::isAvailable(),
  open = rlang::is_interactive(),
  fields = list()
)

Arguments

path

Path

rstudio

Boolean - Use RStudio?

open

Boolean - Open?

fields

passed to usethis::use_description()'s fields argument.

Value

RStudio project (side-effect)


Create RStudio Project

Description

Create RStudio Project

Usage

create_rstudio_project(name, path = ".", ...)

Arguments

name

name of project

path

defaults to "."

...

passed to render_template()'s data argument

Value

same as usethis::create_package().


Vector of character strings from list of unquoted names

Description

Vector of character strings from list of unquoted names

Usage

cs(...)

Arguments

...

dots to quote and c().

Returns a vector of character strings from list of unquoted names. (Copied directly from the Hmisc package).

Examples

cs(a,cat,dog)

Open Date Formatting man page.

Description

Because I always forget.

Usage

date_formats()

Vectors of colors for figures

Description

Creates different vectors of related colors that may be useful for figures.

Usage

default_colors()

Value

Vector of character strings representing colors, in RGB.

Examples

plot(1:4,rep(1,4),col=default_colors(),pch=19,cex=5)
plot(1:16,rep(1,16),col=default_colors(),pch=19,cex=5)

Prints framework for documenting a data frame

Description

Prints the standard fframework for documenting a data frame in an R package.

Usage

document_df(df, num_spaces = 4)

Arguments

df

data frame object; can be a data.frame, data.table, or tibble

num_spaces

number of a spaces per tab; default is 4

Value

nothing

Examples

set.seed(0)
dat <- data.frame(x = c(LETTERS[1:5]),
                  y = c(sample(1:100, 5)))
document_df(dat)

Download Button

Description

Download button without opening up new window in browser when downloaded.

Usage

download_bttn(outputId, label = "Download", class = NULL, icon = NULL, ...)

Arguments

outputId

output id

label

label

class

class

icon

icon

...

passed to tags$a

Value

download button HTML


editenv

Description

quickly edit .Renviron

Usage

editenv()

editprof

Description

Quickly edit .Rprofile

Usage

editprof()

Create a Skeleton 'Grid' for Data based on combinations of unique column values

Description

Create a Skeleton 'Grid' for Data based on combinations of unique column values

Usage

expand_from_vars(data, vars)

Arguments

data

data.frame

vars

variables to use

Value

expanded data.frame


Extract all characters in a string after a match

Description

If a string has more than one match, this will only return the first one.

Usage

extract_after(full_string, after_string, trim_spaces = TRUE)

Arguments

full_string

The full character string to extract from.

after_string

A pattern specifying the string should be extracted after this.

trim_spaces

logical T/F, if there are any spaces within the extracted string, they will be removed. Default is TRUE.

Value

A string

Examples

extract_after("What does the fox say?", after_string = "What does the")

Extract all characters in a string before a match

Description

If a string has more than one match, this will only return the first one.

Usage

extract_before(full_string, before_string, trim_spaces = TRUE)

Arguments

full_string

The full character string to extract from.

before_string

A pattern specifying the string should be extracted before this.

trim_spaces

logical T/F, if there are any spaces within the extracted string, they will be removed. Default is TRUE.

Value

A string

Examples

extract_before("What does the fox say?", before_string = "say")

Extract a portion of a string between two patterns

Description

If a string has more than one match, this will only return the first one.

Usage

extract_between(full_string, after_string, before_string, trim_spaces = TRUE)

Arguments

full_string

The full character string to extract from.

after_string

A pattern specifying the string should be extracted after this.

before_string

A pattern specifying the string should be extracted before this.

trim_spaces

logical T/F, if there are any spaces within the extracted string, they will be removed. Default is TRUE.

Value

A string

Examples

extract_between("What does the fox say?", after_string = "What does the", before_string = "say")

Extract Date

Description

Extracts dates from a character string with format "mm-dd-yyyy" or "mm/dd/yyyy".

Usage

extract_date(string)

Arguments

string

character string

Value

date object

Examples

extract_date("data-raw/lossrun-as-of-2019-01-31.xlsx")

Extract numbers from a string

Description

Extract numbers from a string

Usage

extract_num(string)

Arguments

string

String to pull numbers from

Value

String of numbers


Feedback Message Utility Functions

Description

A set of helper functions for providing verbose feedback to the developer using this packages functions.

This function allows a package developer to automatically add these functions to their package.

Usage

use_feedback_helpers(pkg = ".")

msg_field(x)

msg_value(x)

msg_done(x)

msg_bullet(x, bullet = cli::symbol$bullet)

msg_err(x)

msg_path(x)

msg_info(x)

msg_code(x)

msg_feedback(x)

Arguments

pkg

Package - defaults to "."

x

The string passed to various msg_ functions.

bullet

What to use for the message's bullet. Defaults to cli::symbol$bullet

See Also

Other Feedback Utilities: indent(), inform()


Determine Operating System (OS)

Description

Determine the operating system (OS) of your machine.

Usage

get_os()

is_32bit_os()

is_64bit_os()

Value

OS name in lower case: windows, mac, linux, etc.

See Also

https://www.r-bloggers.com/identifying-the-os-from-r/

Examples

get_os()

Get RStudio Projects

Description

Pulls projects list from RStudio's AppData files.

Usage

get_rstudio_projects(exclude_nonexistant = TRUE)

Arguments

exclude_nonexistant

Defaults to TRUE

Value

data.frame


group_by_occurrence

Description

Group loss data by occurrence ID.

Usage

group_by_occurrence(dat)

Arguments

dat

loss_data by claim ID

Value

data grouped by occurrence

Examples

## Not run: 
dat <- readRDS("data/shiny-data.rds") %>%
  filter(
    eval_dt == as.Date("2018-12-31"),
    member == "Ace Endico Corporation"
  )
test <- by_occurrence(dat)

## End(Not run)

Replace HTML special characters with HTML entities

Description

The characters c("&", '"', "'", "<", ">") will be replaced with c("&amp;", "&quot;", "&#039;", "&lt;", "&gt;"), respectively.

Usage

htmlspecialchars(string)

Arguments

string

the string with (or w/o) HTML special chars

Value

the string with special chars replaced.

References

https://www.php.net/manual/en/function.htmlspecialchars.php

See Also

gsub

Examples

htmlspecialchars("<a href = 'https://yihui.org'>Yihui</a>")
# &lt;a href = &#039;https://yihui.org&#039;&gt;Yihui&lt;/a&gt;

In RStudio

Description

Determine if user is in an RStudio Environment

Usage

in_rstudio()

Value

logical


Indent

Description

Indentation around various msg_ feedback functions.

Usage

indent(x, first = "  ", indent = first)

Arguments

x

The string passed to various msg_ functions.

first

what to indent with - defaults to " ".

indent

indentation of next line - defaults to first

Value

string

See Also

Other Feedback Utilities: feedback, inform()


Inform

Description

A wrapper around rlang::inform() for providing feedback to developers using this packages functions.

Usage

inform(...)

Arguments

...

Arguments passed on to rlang::inform

message

The message to display, formatted as a bulleted list. The first element is displayed as an alert bullet prefixed with ! by default. Elements named "*", "i", "v", "x", and "!" are formatted as regular, info, success, failure, and error bullets respectively. See Formatting messages with cli for more about bulleted messaging.

If a message is not supplied, it is expected that the message is generated lazily through cnd_header() and cnd_body() methods. In that case, class must be supplied. Only inform() allows empty messages as it is occasionally useful to build user output incrementally.

If a function, it is stored in the header field of the error condition. This acts as a cnd_header() method that is invoked lazily when the error message is displayed.

class

Subclass of the condition.

body,footer

Additional bullets.

use_cli_format

Whether to format message lazily using cli if available. This results in prettier and more accurate formatting of messages. See local_use_cli() to set this condition field by default in your package namespace.

If set to TRUE, message should be a character vector of individual and unformatted lines. Any newline character "\\n" already present in message is reformatted by cli's paragraph formatter. See Formatting messages with cli.

.file

A connection or a string specifying where to print the message. The default depends on the context, see the stdout vs stderr section.

.subclass

[Deprecated] This argument was renamed to class in rlang 0.4.2 for consistency with our conventions for class constructors documented in https://adv-r.hadley.nz/s3.html#s3-subclassing.

.frequency

How frequently should the warning or message be displayed? By default ("always") it is displayed at each time. If "regularly", it is displayed once every 8 hours. If "once", it is displayed once per session.

.frequency_id

A unique identifier for the warning or message. This is used when .frequency is supplied to recognise recurring conditions. This argument must be supplied if .frequency is not set to "always".

Value

feedback in console

See Also

rlang::inform()

Other Feedback Utilities: feedback, indent()


is_inst

Description

Check if a package is installed.

Usage

is_inst(pkg)

Arguments

pkg

string: package to search installation path for

Details

This function provides a lightweight alternative to utils::installed.packages() by using nzchar instead.

Value

logical (TRUE/FALSE)

References

Examples

## Not run: 
is_inst("dplyr")

## End(Not run)

Ensures a text string is a valid email address

Description

Ensures a text string is a valid email address

Usage

is_valid_email(x)

Arguments

x

string

Value

logical


Launch a new project-less RStudio session

Description

Call this function as an addin to launch a new project-less RStudio session without closing your currently open RStudio project(s).

Usage

launch_rstudio()

Multi Filt

Description

Filter across multiple variables.

Usage

multi_filt(data, vars, filts)

Arguments

data

data

vars

variables

filts

filters

Details

NOTE: this function currently only supports character and factor level filtering by using the ⁠dplyr::filter(<var> %in% c(<filts>))⁠ syntax. For numeric and date level filtering will need to incorporate expressions like ⁠<= 5⁠ as filt arguments.

Value

a filtered data.frame or tibble.

References

dplyr::filter() rlang tidyeval tidyeval glue syntax

Examples

library(dplyr)
data <- datasets::iris
str(data)

iris_filtered <- multi_filt(data, vars = list("Species"), filts = list(c("setosa", "versicolor")))

str(iris_filtered) # filtered for only Species %in% c("setosa" and "versicolor")

Open local version of pkgdown site for jimstools

Description

Open local version of pkgdown site for jimstools

Usage

open_docs()

Open Github Repository URL

Description

Open Github Repository URL

Usage

open_gh_repo()

Open file in RStudio

Description

Function tries opening a file in RStudio.

Usage

open_in_rstudio(path, ...)

Arguments

path

(sting) Path to file.

...

Further arguments to rstudioapi::navigateToFile().

See Also


Open pkgdown site of the package

Description

Open pkgdown site of the package

Usage

open_pkgdown()

Open RStudio Project

Description

Open RStudio Project

Usage

open_project()

Value

invisibly returns an RStudio project


Operators

Description

Extensions of base operators.

inverse of %in%

Usage

x %notin% vector

x %allin% vector

x %anyin% vector

x %nonein% vector

pattern %partin% vector

Arguments

x

Numeric or character vector.

vector

Numeric or character vector.

pattern

Character string containing regular expressions to be matched.

Value

logical

logical

See Also

base::any(), base::match(), and base::all()

base::grepl()

Examples

data <- data.frame(
  id = 1:10,
  x = as.integer(runif(10, 0, 10))
)

data[data$id %notin% c(1, 3, 5, 7, 9), ]

1:2 %allin% 1:3  # TRUE
3:4 %allin% 1:3  # FALSE
3:4 %anyin% 1:3  # TRUE
4:5 %anyin% 1:3  # FALSE
3:4 %nonein% 1:3  # FALSE
4:5 %nonein% 1:3  # TRUE
"Bei" %partin% c("Beijing", "Shanghai")  # TRUE
"bei" %partin% c("Beijing", "Shanghai")  # FALSE
"[aeiou]ng" %partin% c("Beijing", "Shanghai")  # TRUE

Paste Winslash - Addin Function

Description

Paste Winslash - Addin Function

Usage

paste_winslash()

Details

assign to keyboard shortcut Ctrl + Shift + P for easy access.

Value

normalized path character string


Pull all unique values for a variable

Description

Pull all unique values for a variable

Usage

pull_unique(data, var, sort = TRUE, decreasing = FALSE, names = TRUE)

Arguments

data

data.frame

var

variable name

sort

logical (default = TRUE)

decreasing

logical (default = FALSE)

names

logical (default = TRUE)

Value

vector


htable Create a quick html table using my favorites options for DT::datatable()

Description

htable Create a quick html table using my favorites options for DT::datatable()

Usage

quick_table(df, ...)

Arguments

df

data.frame to display

...

options sent through to DT::datatable

Examples

quick_table(mtcars)

Generate a random password with a specified length

Description

This function generates a random passord sampled from the ASCII table.

Usage

random_password(length = 12, replace = FALSE, extended = TRUE)

Arguments

length

length of the password

replace

sample from the ASCII table with (TRUE) or without (FALSE) replacement?

extended

if FALSE, use alphanumeric characters only; otherwise use all the ASCII characters

Value

a character string

See Also

sample

Examples

random_password()
# set the seed to get fixed password every time; you may just remember the
# seed and forget the real password because it's reproducible
set.seed(123)
random_password()
# long password
random_password(20, TRUE)

Render Template

Description

Renders a template using whisker::whisker.render() for templates used in a fashion similar to usethis::use_template().

Usage

render_template(template_path, out_path, data = list(), open = TRUE)

Arguments

template_path

Path to template

out_path

Path to output the rendered template

data

list to pass to whisker::whisker.render()

open

boolean - open template after it renders?

Value

invisible


save_pdf

Description

Copies the graphics contents of current device to PDF (a wrapper for dev2.pdf). Default size is 8.5 x 11 in landscape mode.

Usage

save_pdf(file, width = 11, height = 8.5, jpg = FALSE)

Arguments

file

filename to save the image

width

width of pdf image

height

height of pdf image

jpg

convert to 300 dpi .jpg file after pdf save?


Set working directory to the path of current script

Description

Set working directory to the path of current script

Usage

set_wd(dir = NULL)

Arguments

dir

NULL (default) or a character string specifying the working directory.

If NULL, set working directory to the path of the current R script.

See Also

setwd

Examples

## Not run: 
set_wd()  # set working directory to the path of the current R script

set_wd("D:/")  # "\" is not allowed, you should use "/"

set_wd("../")  # set working directory to the parent directory

## End(Not run)

Shiny Icons

Description

Shiny Icons

Usage

shiny_icons()

Value

character vector of shiny package icons


Shut down the operating system with the command ‘shutdown’

Description

There is a command shutdown in both Windows and Linux, and this function uses it to shut down a computer.

Usage

shutdown(wait = 0)

Arguments

wait

time to wait before shutting down (in seconds); passed to Sys.sleep

Details

After the time wait has passed, R will execute shutdown -s -t 0 (for Windows) or shutdown -h now to shut down the computer.

Value

The status code of system.

See Also

system, Sys.sleep

Examples

if (interactive()) {
# when your code is extremely time-consuming, you may need this function;
# e.g. you go to sleep, and R is running long computation...
# complex graphics... and long long computation... at last,
shutdown()
# the next day you wake up, "thank you, R" :)
}

R Startup Functions

Description

Use these utility functions to quickly edit your .Rprofile, .Renviron, or other startup files.

Usage

editrprof(scope = c("user", "project"))

editrenv(scope = c("user", "project"))

Arguments

scope

scope - user or project

Value

invisible

See Also

See base::Startup() for details on the R specific startup process.


GitHub Linguist Exclusions

Description

This function creates a .gitattributes file in the root of your project in order to exclude certain file types from being detected as a certain programming language on GitHub. See details for more information.

Usage

use_gh_linguist(excludes = c("*.js", "*.html", "*.css"))

Arguments

excludes

Character vector of wildcards indicating extensions to be labelled as linguist-vendored and ignored by GitHub's language detector github-linguist.

Details

By default this function will write ⁠*.js⁠, ⁠*.html⁠, and ⁠*.css⁠ to a .gitattributes file in order for github-linguist to ignore Javascript, HTML, and CSS languages in your repositories language section.

The resulting file will look like so:

# github linguist exclusions:
*.js linguist-vendored
*.html linguist-vendored
*.css linguist-vendored

Value

invisibly returns the text written to .gitattributes

Examples

## Not run: 
use_gh_linguist()

## End(Not run)

Get User-Related Information

Description

Get user-related information.

Usage

user_info()

Value

invisibly returns os_info vector

Examples

user_info()

view_list

Description

Interactive view of list structures with listviewer::jsonedit()

Usage

view_list(list, ...)

Arguments

list

list to display

...

options sent through to listviewer::jsonedit()

Examples

view_list(mtcars)