Package 'k5'

Title: Kiernan Nicholls Miscellaneous
Description: Quality of life functions for interactive programming. Shortcuts for common combinations of functions or different default arguments. Not to be used in production level scripts, but useful for exploring and quickly manipulating data for easy analysis. Also imports a variety of packages to facilitate the installation of those imported packages on the host machine.
Authors: Kiernan Nicholls [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-9229-7897>)
Maintainer: Kiernan Nicholls <[email protected]>
License: GPL-3
Version: 0.2.1
Built: 2026-10-14 11:25:00 UTC
Source: https://github.com/k5cents/k5

Help Index


Inverted match

Description

⁠%out%⁠ is an inverted version of the infix %in% operator.

Usage

x %out% table

Arguments

x

vector: the values to be matched. Long vectors are supported.

table

vector or NULL: the values to be matched against.

Details

⁠%out%⁠ is currently defined as "%out%" <- function(x, table) match(x, table, nomatch = 0) == 0

Value

logical; if x is not present in table

Examples

c("A", "B", "3") %out% LETTERS

Convert contract names to factor intervals

Description

Can perform one of three rough conversions:

  1. For interval contracts (e.g., "220 - 229", "9% or more", etc.), convert the character strings to proper interval notation.

  2. For contracts with multiple discrete outcomes (e.g., Candidate names), convert the character vector to simple factors.

  3. For markets with a single binary question (e.g., "Will the Democrats have a brokered convention in 2020?"), contracts returned are always "Yes" which is converted to TRUE.

Usage

contract_convert(x, decimal = FALSE)

Arguments

x

A character vector of contract names.

decimal

Should percentages be converted to decimals?

Value

A interval factor, unique factor, or logical vector.


Copy the last object to the clipboard

Description

Use clipr::write_clip() to write the last value as a character vector to the system clipboard.

Usage

copy_last(x = .Last.value)

Arguments

x

The object to view, usually left as base::.Last.value.

Details

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value before further processing (e.g., printing).

Value

The same .Last.value as before copied, invisibly.


Count set difference

Description

Find the length of the set of difference between x and y vectors.

Usage

count_diff(x, y, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

sum(x %out% y)

Value

The number of unique values of x not in y.

See Also

Other counting wrappers: count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

# only unique values are checked
count_diff(c("VT", "NH", "ZZ", "ZZ", "ME"), state.abb)

Count in

Description

Count the total values of x that are %in% the vector y.

Usage

count_in(x, y, na.rm = TRUE, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

na.rm

logical; Should NA be ignored?

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

sum(x %out% y)

Value

The sum of x present in y.

See Also

Other counting wrappers: count_diff(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

count_in(c("VT", "NH", "ZZ", "ME"), state.abb)

Count missing

Description

Count the total values of x that are NA.

Usage

count_na(x)

Arguments

x

A vector to check.

Details

sum(is.na(x))

Value

The sum of x that are NA

See Also

Other counting wrappers: count_diff(), count_in(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

count_na(c("VT", "NH", NA, "ME"))

Count out

Description

Count the total values of x that are are ⁠%out%⁠ of the vector y.

Usage

count_out(x, y, na.rm = TRUE, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

na.rm

logical; Should NA be ignored?

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

sum(x %out% y)

Value

The sum of x absent in y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

count_out(c("VT", "NH", "ZZ", "ME"), state.abb)

Count the way you want

Description

A wrapper around dplyr::count() with sort set to TRUE by default and the an additional column created by default containing the proportional fraction each observation makes of the whole.

Usage

count2(x, ..., wt = NULL, sort = TRUE, prop = TRUE, sum = NULL)

count_vec(x, sort = TRUE, prop = TRUE, sum = NULL)

Arguments

x

A data frame.

...

Variables to group by.

wt

Frequency weights.

sort

If TRUE, will show the largest groups at the top.

prop

If TRUE, compute the fraction of marginal table.

sum

Column to replace with a cumulative sum (n, p, or np).

Value

A tibble of element counts

Examples

count2(iris, Species)

File modification date age

Description

The period of time since a system file was modified.

Usage

file_age(...)

Arguments

...

Arguments passed to file.info(), namely character vectors containing file paths. Tilde-expansion is done: see path.expand().

Value

A Period class object.

Examples

file_age(system.file("README.md", package = "campfin"))

File Encoding

Description

Call the file command line tool with option -i.

Usage

file_encoding(path)

Arguments

path

A local file path or glob to check.

Value

A tibble of file encoding.


Filter a data frame by a regular expression

Description

A shortcut for dat %>% filter(str_detect(column, "\\d")).

Usage

filter_rx(dat, col, pattern, ...)

Arguments

dat

A data frame with a character column to filter.

col

The column containing a character vector to input.

pattern

Pattern to look for..

...

Additional arguments passed to stringr::str_detect().

Value

A subset of rows from dat.


GAA Team Abbreviations by Season and Team ID

Description

GAA Team Abbreviations by Season and Team ID

Usage

gaa

Format

A data frame with 74 rows and 3 variables:

seasonId

The fantasy season integer

teamId

The team ID integer

abbrev

The normalized owner abbreviation for that year

...


GAA As-Played Score History by Matchup Period

Description

Every fantasy matchup in ESPN league 252353 since the league began in 2015, scored the way it was scored when it was played.

Usage

gaa_scores

Format

A data frame with 1,524 rows and 20 variables:

seasonId

The fantasy season integer

matchupPeriodId

Matchup period; playoff matchups span two NFL weeks

matchupId

Matchup identifier within the season

teamId

The ESPN team ID, which is recycled between owners

abbrev

The normalized owner abbreviation, see gaa

opponent

The opposing owner's abbreviation

isHome

Whether the team was nominally the home side

isRegular

Whether the matchup is a regular season game

playoffTierType

NONE, WINNERS_BRACKET, or a consolation ladder

totalPoints

Points scored, under the scoring in force at the time

espnPoints

Points the ESPN API reports for this matchup today

kickerAdj

totalPoints minus espnPoints; zero outside 2022

isWinner

Won the head-to-head matchup as played; NA for a tie

outcome

WIN, LOSS, or TIE, preserving ties

espnWinner

Won the matchup according to ESPN's current scores

corrected

Whether the rescore changed this matchup's result

medianLine

The league median score for that regular season week

medianWin

Scored above the median; NA for a score exactly on it

medianOutcome

WIN, LOSS, or TIE against the median

expectedWins

Ascending rank among that week's scores, 0 to 1

Details

ESPN serves a revised 2022 season. Kicker scoring was changed to per-yard (statId 214 at 0.1) before the 2023 season, and ESPN recomputed 2022 under the new table. That flipped one game – week 1, KIER over ANGS by 0.02 points as played, ANGS by 0.08 as ESPN now reports it – which moved the 4 seed from KIER to CART and, through the bracket, the championship from KIER to CHAR. No other season is affected. Adjustments are in data-raw/gaa_corrections.csv and were derived by re-scoring raw player stats under the 2021 scoring table.

Nothing is overwritten: totalPoints is the as-played score, espnPoints is what the API returns today, and kickerAdj is the difference, so either version can be recovered. isWinner and espnWinner pair the same way.

Playoff rows hold as-played scores under the bracket ESPN actually ran, which was seeded from the revised standings. They are not re-bracketed, so tallying winners of the final matchup period still credits 2022 to CHAR. The counterfactual bracket is an inference and deliberately not baked in here.

medianWin reconstructs the league median game – a second win each week for scoring in the top half – for every season, including the ones before the league switched it on in 2022, so the eras can be compared on one basis.

Source

ESPN league 252353 via fflr::ffl_api()

See Also

gaa_weekly for the same scores split by NFL week


GAA As-Played Score History by NFL Week

Description

The same corrected scores as gaa_scores, split by scoringPeriodId rather than rolled up to matchup periods. Regular season matchups cover one week each, so the two agree there; playoff matchups span two weeks and are only separable here. See gaa_scores for the 2022 rescore this corrects.

Usage

gaa_weekly

Format

A data frame with 1,732 rows and 11 variables:

seasonId

The fantasy season integer

scoringPeriodId

The NFL week

matchupPeriodId

The matchup period this week belongs to

matchupId

Matchup identifier within the season

teamId

The ESPN team ID, which is recycled between owners

abbrev

The normalized owner abbreviation, see gaa

isHome

Whether the team was nominally the home side

playoffTierType

NONE, WINNERS_BRACKET, or a consolation ladder

points

Points scored that week, under the scoring in force then

espnPoints

Points the ESPN API reports for that week today

kickerAdj

points minus espnPoints; zero outside 2022

Source

ESPN league 252353 via fflr::ffl_api()

See Also

gaa_scores for matchup-level records and the median game


Return the last value

Description

A function shortcut for accessing .Last.value.

Usage

last_value(x = .Last.value)

Arguments

x

The object to return, usually left as base::.Last.value.

Details

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value (in package:base) before further processing (e.g., printing).

Value

The same .Last.value as before viewing, invisibly.


Save and load packages from file

Description

Save and load packages from file

Usage

load_my_packages(path = NULL)

save_my_packages(x = NULL, path = tempfile())

Arguments

path

The path to a text file containing one package per line. If NULL (default), then the default list is read from k5/inst/PACKAGES.

x

A character vector of package names to save. If NULL (default), use all currently attached packages.

Value

The list of packages, invisibly.


Remove in

Description

Set NA for the values of x that are %in% the vector y.

Usage

na_in(x, y, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Value

The vector x missing any values in y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

na_in(c("VT", "NH", "ZZ", "ME"), state.abb)
na_in(1:10, seq(1, 10, 2))

Remove out

Description

Set NA for the values of x that are ⁠%out%⁠ of the vector y.

Usage

na_out(x, y, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Value

The vector x missing any values not in y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

na_out(c("VT", "NH", "ZZ", "ME"), state.abb)
na_out(1:10, seq(1, 10, 2))

Remove repeated character elements

Description

Set NA for the values of x that contain a single repeating character and no other characters.

Usage

na_rep(x, n = 0)

Arguments

x

A vector to check.

n

The minimum number times a character must repeat. If 0, the default, then any string of one character will be replaced with NA. If greater than 0, the string must contain greater than n number of repetitions.

Details

Uses the regular expression "^(.)\\1+$".

Value

The vector x with NA replacing repeating character values.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

na_rep(c("VT", "NH", "ZZ", "ME"))

Proportion missing

Description

Find the proportion of values of x that are distinct.

Usage

prop_distinct(x)

Arguments

x

A vector to check.

Details

length(unique(x))/length(x)

Value

The ratio of distinct values x to total values of x.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_in(), prop_na(), prop_out(), what_in(), what_out()

Examples

prop_distinct(c("VT", "VT", NA, "ME"))

Proportion in

Description

Find the proportion of values of x that are %in% the vector y.

Usage

prop_in(x, y, na.rm = TRUE, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

na.rm

logical; Should NA be ignored?

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

mean(x %in% y)

Value

The proportion of x present in y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_na(), prop_out(), what_in(), what_out()

Examples

prop_in(c("VT", "NH", "ZZ", "ME"), state.abb)

Proportion missing

Description

Find the proportion of values of x that are NA.

Usage

prop_na(x)

Arguments

x

A vector to check.

Details

mean(is.na(x))

Value

The proportion of values of x that are NA.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_out(), what_in(), what_out()

Examples

prop_na(c("VT", "NH", NA, "ME"))

Proportion out

Description

Find the proportion of values of x that are ⁠%out%⁠ of the vector y.

Usage

prop_out(x, y, na.rm = TRUE, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

na.rm

logical; Should NA be ignored?

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

mean(x %out% y)

Value

The proportion of x absent in y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), what_in(), what_out()

Examples

prop_out(c("VT", "NH", "ZZ", "ME"), state.abb)

Read a table from the clipboard

Description

Use readr::read_delim() on a string copied to the clipboard. Defaults to tab separator like given when copying cells from spreadsheets.

Usage

read_delim_clip(delim = "\t", ...)

Arguments

delim

Single character used to separate fields within a record.

...

Additional arguments passed to readr::read_delim().

Value

A data frame read from the clipboard.


Read a text file without column guessing

Description

Use readr::read_delim() without specifying any column types. All columns are treated as character strings.

Usage

read_delim_dumb(file, delim = c(",", "\t", "|"), ...)

read_csv_dumb(file, ...)

read_tsv_dumb(file, ...)

Arguments

file

Either a path to a file, a connection, or literal data.

delim

Single character used to separate fields within a record.

...

Additional arguments passed to readr::read_delim().

Value

A tibble data frame read from the file.


Apply a statistic function to all variables

Description

Apply either count_na() or dplyr::n_distinct() to every column of a data frame and return the count and share of total values (either proportion missing or proportion distinct).

Usage

var_missing(df)

var_distinct(df)

Arguments

df

A data frame to glimpse.

Value

Invisibly, a table of statistics by column of a data frame.

Examples

var_missing(dplyr::storms)
var_distinct(dplyr::storms)

View an HTML document in Firefox

Description

Take an XML document object, write to an HTML file, and open in Firefox.

Usage

view_firefox(html)

Arguments

html

An object which has the class xml_document, often from rvest.

Value

The html object, invisibly.


View the last object

Description

Invoke a spreadsheet-style data viewer on a matrix-like R object. In a non-interactive session, the object is returned invisibly and nothing is "viewed".

Usage

view_last(x = .Last.value)

Arguments

x

The object to view, usually left as base::.Last.value.

Details

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value before further processing (e.g., printing).

Value

The same .Last.value as before viewing, invisibly.


Which in

Description

Return the values of x that are %in% of the vector y.

Usage

what_in(x, y, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

x[which(x %in% y)]

Value

The elements of x that are %in% y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_out()

Examples

what_in(c("VT", "DC", NA), state.abb)

Which out

Description

Return the values of x that are ⁠%out%⁠ of the vector y.

Usage

what_out(x, y, na.rm = TRUE, ignore.case = FALSE)

Arguments

x

A vector to check.

y

A vector to compare against.

na.rm

logical; Should NA be ignored?

ignore.case

logical; if FALSE, the pattern matching is case sensitive and if TRUE, case is ignored during matching.

Details

x[which(x %out% y)]

Value

The elements of x that are ⁠%out%⁠ y.

See Also

Other counting wrappers: count_diff(), count_in(), count_na(), count_out(), na_in(), na_out(), na_rep(), prop_distinct(), prop_in(), prop_na(), prop_out(), what_in()

Examples

what_out(c("VT", "DC", NA), state.abb)

Count file words, lines, and bytes

Description

Invoke system tool to print newline, word, and byte counts for each file.

Usage

word_count(path, count = "")

Arguments

path

Character vector of file paths.

count

The type of element to count, see details.

Details

One of five options or an empty string (default):

  1. "lines" for newline characters (separating lines).

  2. "words" for words separated by white space.

  3. "chars" for individual characters.

  4. "bytes" for total bytes, differs with multibyte characters.

  5. "max" for the maximum display width of longest line.

Value

A data frame of counts by file.


Write a table from the clipboard

Description

Use readr::format_delim() on a data frame to copy a string to the clipboard. Defaults to tab separator like given when copying cells from spreadsheets.

Usage

write_delim_clip(x, delim = "\t", ...)

Arguments

x

A data frame to write to clipboard.

delim

Single character used to separate fields within a record.

...

Additional arguments passed to readr::format_delim().

Value

Invisibly, the input data frame.


Write the last value to disk

Description

The value of the internal evaluation of a top-level R expression is always assigned to .Last.value before further processing (e.g., printing).

Usage

write_last(file = tempfile(), x = .Last.value, ...)

save_last(file = tempfile(), x = .Last.value, ...)

Arguments

file

File or connection to write to.

x

The object to write, usually left as base::.Last.value.

...

Additional arguments passed to the writing function (see Details).

Details

Four types of files are written, based on object class:

  1. For data frames, a tab-separated file via readr::write_tsv().

  2. For vectors, a newline-separated file via readr::write_lines().

  3. For ggplots, a raster image (by default) via ggplot2::ggsave().

  4. For other objects, an uncompressed data file via readr::write_rds().

Value

The created file path, invisibly.