Package 'ktools'

Title: Tools for Tracing, Shiny Routing, and JavaScript Dependencies
Description: Provides utility tools designed to homogenize development patterns across projects. This includes specialized tracing utilities, mechanisms for generating unique identifiers, JavaScript dependency management, targeting unique input from multiple HTML tags within Shiny apps and more.
Authors: Philippe Peret [aut, cre, cph] (ORCID: <https://orcid.org/0009-0003-9666-7490>)
Maintainer: Philippe Peret <[email protected]>
License: GPL (>= 3)
Version: 0.9.10
Built: 2026-10-08 16:58:41 UTC
Source: https://github.com/thekangaroofactory/ktools

Help Index


Conditional Output

Description

This wrapper function aims at enabling a trace level mechanism that relies on the cat function.

Usage

catl(..., level = 1, debug = Sys.getenv("TRACE_LEVEL"), newline = TRUE)

Arguments

...

R objects as defined in cat

level

a numeric value indicating the level of trace

debug

an optional (usually omitted) value to indicate the level of trace to be displayed

newline

a logical. If TRUE (default), new line "\n" will be added

Details

The goal is to provide a trace level mechanism that can be disabled in a production context (as printing output to the console or file is costly).

The different levels are left flexible.

By default, debug is set to Sys.getenv("TRACE_LEVEL") If the environment variable is not set, no output will be produced (silent mode) When the variable is set, the function will pass calls with level <= debug to the original cat function.

The trace_level function can be used to activate a specific trace level.

Value

None (invisible NULL).

Examples

# silent unless TRACE_LEVEL is set
catl("Awesome message here")

# force print no matter if TRACE_LEVEL is set
catl("Awesome message here", debug = 1)

# demonstrate trace levels
catl("Awesome message here", level = 2, debug = 1)
catl("Awesome message here", level = 1, debug = 2)

Copy Package Template Files.

Description

Copy Package Template Files.

Usage

copy_template(template, pkg = "ktools", path = getwd(), filename = NULL)

Arguments

template

the name of the template file to be copied.

pkg

the name of the package where to find the template.

path

destination path where to copy the template (default = working directory).

filename

an optional name for the copy.

Details

By default, the function addresses templates delivered along with this package (i.e. pkg = "ktools").

When filename is not provided, the copy will have same name as the template without the "template_" prefix pattern.

An error will be thrown if the template file is not found.

Value

a logical (see file.copy()

Examples

## Not run: 
copy_template(template = "template_shiny_server.R", path = "shinyapp", filename = "my_server.R")

## End(Not run)

Code Stats

Description

Builds a basic code counts report.

Usage

count_lines(con, verbose = FALSE)

Arguments

con

a connection object or a character string (passed to readLines).

verbose

a logical (FALSE by default) if counts should be printed to the console.

Details

The report will contain the following information:

  • total

  • code

  • comment

  • documentation

  • spacing

Code lines ending with a comment are counted as code lines (hence ignored from comments).

Value

a named vector.

See Also

scan_code()

Examples

infile <- tempfile()

lines <- "#' This\n#'\n\n# comment\np <- 1\n\nif(p==1) print(p)\n"

writeLines(lines, infile)
count_lines(infile)

Create Data

Description

Build an empty data.frame from a vector of colClasses.

Usage

create_data(colClasses)

Arguments

colClasses

a named vector of classes.

Details

The names of the vector will be used to name the columns and the values to cast the columns to the given classes.

If NA is given as input for colClasses, then read.table() will return an empty data.frame (0 obs. of 0 variables)

Value

a data.frame.

Examples

create_data(colClasses = c(id = "numeric", date = "Date", comment = "character"))

Date Range

Description

Compute specific range between two dates.

[Deprecated]

Usage

date_range(min, max, type = "this_year")

Arguments

min

a Date for the lower value.

max

a Date for the higher value.

type

an optional character vector, to set the strategy (default = "this_year").

Value

a Date vector c(start, end).

Examples

## Not run: 
date_range(min = Sys.Date()-365, max = Sys.Date()+365, type = "this_year")

## End(Not run)

Filter by Date Range

Description

Filter a data.frame by specific date range.

Usage

filter_date(x, colname = NULL, ref = Sys.Date(), unit = "month")

Arguments

x

a data.frame with a Date or POSIXct column.

colname

an optional character string, the name of the column to use in filter.

ref

an optional Date value to be used as a reference for the date range.

unit

a string to compute the date range (default = "month") (see round_date).

Details

The purpose of this function is to make data navigation between date range easier. By default, it will filter the input data.frame to keep dates belonging to the current month.

When colname = NULL (the default), it will look for a 'date' column in x.

Value

a filtered data.frame.

Examples

# -- this month (the default)
filter_date(data.frame(date = Sys.Date() - runif(n = 10, min = -50, max = 50)))

# -- previous month
filter_date(data.frame(date = Sys.Date() - runif(n = 10, min = -50, max = 50)),
ref = Sys.Date() - as.integer(format(Sys.Date(), "%d")))

Package Function in Do Call

Description

Trick to solve the use of :: for package functions in do.call()

Usage

getNsFunction(x)

Arguments

x

the name of the function, most probably as pkg::fun()

Value

the exported function name in namespace pkg

Examples

## Not run: 
getNsFunction("pkg::fun")

## End(Not run)

Compute Timestamp

Description

Compute a numeric timestamp.

Usage

getTimestamp(k = 1000, digits = 0, silent = FALSE)

Arguments

k

a numeric (default = 1000), used as a multiplication factor.

digits

an integer (default = 0) to round the value.

silent

an optional (default = FALSE) logical. If TRUE, no traces will go to the console.

Details

By default (k = 1000), the function returns a numeric up to the millisecond.

Output should not be used as a unique id if users / systems may call it more than one time per millisecond.

Value

a numeric.

See Also

uuid()

Examples

# compute up to the second timestamp
getTimestamp(k = 1, digits = 0)

# compute up to the millisecond timestamp
getTimestamp(k = 1000)
getTimestamp()

Find Date Column(s)

Description

Detects Date and/or POSIXct column(s) in a data.frame.

Usage

has_date(x, single = TRUE)

Arguments

x

a data.frame object.

single

a logical (default TRUE) if it should return only the first column.

Value

the name of the column(s) or NA if no date column is found.

Examples

has_date(data.frame(date = Sys.Date()))
has_date(data.frame(date = Sys.Date(), update = Sys.Date()), single = FALSE)
has_date(data.frame(date = Sys.Date(), update = Sys.Date()), single = TRUE)

Indented Cat

Description

[Experimental]

Usage

incat(x, sep = "")

Arguments

x

R objects.

sep

a character vector of strings to append after each element (default is "").

Details

When the function detects a direct call (i.e. not from another function), then it basically just do cat otherwise it finds the calling function name and print indented output based on callstack position.

Value

None (invisible NULL).

Examples

# default
incat("direct call")

# call from different levels
foo <- function() incat("inside foo")
bar <- function() {incat("inside bar"); foo()}

foo()
bar()

Decode Input Value

Description

Split an input value into a named vector.

Usage

input_decode(x)

Arguments

x

the (input) value to decode.

Details

The function is used together with action_link() / onclick_event() when their value is left to the HTML tag id.

The expected pattern for x is "namespace-action_value" or "action_value". More complex use cases should be covered using a list value in action_link().

Value

a named vector c(namespace, action, value) or c(action, value).

Examples

input_decode("module1-add_leg_896")
input_decode("add_leg_896")

Match Lists

Description

Matches a named list against a reference.

Usage

match.list(x, reference)

Arguments

x

a named list to check.

reference

a named list to use as a reference.

Details

The function will drop any element from x that does not fit with a name found in reference and add missing ones.

It will also check that elements in x have same classes as matching element in reference.

Value

a list.

Examples

match.list(x = list(foo = 1), reference = list(foo = 0, bar = "dummy"))

Match Options

Description

Matches a named list against the one expected in function arguments.

Usage

match.option(fun, arg, value)

Arguments

fun

the reference of the function, without ().

arg

the name of the argument to test.

value

the value to test.

Value

The list of options, including missing ones.

Examples

# function expecting a list as argument
foo <- function(options = list(a = 1, b = 2)){}

# match user input
match.option(foo, "options", list(a = 1))

Build onClick Event

Description

This function helps building onclick event to pass complex instructions to a given listener. This is particularly useful when working with lists of links, most probably generated within an apply instruction over a data.frame.

Usage

onclick_event(target, value = "this.id", namespace = NULL, event = TRUE)

Arguments

target

the input to update on click.

value

the value to send to the input (see details).

namespace

the id of the module to target if so.

event

should Shiny treat it as an event.

Details

target defines the name of the input entry to update (i.e. input$target).

value will be passed to the target input. By default, it will send the id of the HTML tag (ex: actionLink, actionButton).

This behavior can be tuned to send a more complex instruction. In particular, a list can be passed to the target input (see example).

Value

a character string.

See Also

action_link()

Examples

## Not run: 
# baseline:
# input$btn_clicked will get the id of the html tag
onclick_event(target = "btn_clicked")

# custom value:
# input$btn_clicked will get "foo"
onclick_event(target = "btn_clicked", value = "foo")

# custom list:
# input$btn_clicked will get the list
onclick_event(target = "btn_clicked", value = list(a = "foo", b = "bar"))

# -- shiny module:
# input$btn_clicked inside "module_id" will get 12
onclick_event(target = "btn_clicked", value = 12, namespace = "module_id")

## End(Not run)

Scan Code

Description

Generates a code report for a given path.

Usage

scan_code(path = getwd())

Arguments

path

a path to scan.

Value

a data.frame.

See Also

count_lines()

Examples

## Not run: 
scan_code()
## End(Not run)

Sequence of Timestamps

Description

[Deprecated]

Usage

seq_timestamp(n = 2)

Arguments

n

the desired output vector length.

Value

a numeric vector of timestamps.

Examples

## Not run: 
seq_timestamp(n = 2)
## End(Not run)

Shiny Outputs

Description

Wrapper around Shiny *Output functions.

Usage

simple_ui(id, output, type = "ui", ...)

Arguments

id

the id of the module.

output

the name of the output.

type

the type of output: "ui" (default), "text", "plot", "table".

...

other arguments to pass to the *Output function.

Details

id can be a vector of ids in case of sub module.

Value

an HTML tag.

Examples

simple_ui(id = "my_module", output = "my_output")

Source Code

Description

Source all files from a given path.

Usage

source_code(path, verbose = FALSE)

Arguments

path

a character vector of the path to explore.

verbose

a logical value (default = FALSE). If TRUE, then details about sourced files will be sent to the console.

Details

Given path is explored with "*.R" extension pattern. Sub-directories will be explored as well.

Value

an integer, how many functions have been attached to the environment.

Examples

## Not run: 
source_code("./R")

## End(Not run)

Capitalize First Letters

Description

Capitalize First Letters

Usage

toupper_words(s, strict = FALSE)

Arguments

s

a character string.

strict

a logical (default = FALSE) if other characters should be forced to lower.

Value

a character string.

Examples

toupper_words("this is an example")

Capitalize First Letter

Description

Capitalize First Letter

Usage

toupperfirst(x)

Arguments

x

a character vector, or an object that can be coerced to character by as.character.

Value

a character vector.

Examples

toupperfirst("capitalize first letter")
toupperfirst(1)

Trace Level

Description

A helper function to get/set the trace level printed by catl().

Usage

trace_level(level = NULL)

Arguments

level

an integer (or NULL).

Details

level is used to define the level of trace printed by catl(). Use 0 to set the trace OFF or NULL to get the current trace level.

Value

Nothing or the active trace level.

See Also

catl()

Examples

trace_level()
trace_level(2)
trace_level(0)

Update .Renviron File

Description

Add an environment variable to the project.

Usage

update_r_environ(path = getwd(), key, value)

Arguments

path

the path to the .Renviron file (default is working directory).

key

a character string for the name of the variable.

value

the value to be assigned to the variable.

Value

a logical (TRUE if success, else FALSE)

See Also

use_r_environ()

Examples

## Not run: 
update_r_environ(key = "MY_VAR", value = "my_value")

## End(Not run)

Use Plot Theme

Description

Create a theme function that can be used across a project.

Usage

use_plot_theme(path = getwd())

Arguments

path

where to copy the template.

Value

a logical.

Examples

## Not run: 
use_plot_theme()

## End(Not run)

Create .Renviron File

Description

Create .Renviron File

Usage

use_r_environ(path = getwd())

Arguments

path

the path where to create the file.

Details

By default, path is set to the working directory.

Value

a logical (see file.create())

See Also

update_r_environ()

Examples

## Not run: 
use_r_environ()

## End(Not run)

Generate Uuid

Description

Compute unique identifier.

Usage

uuid()

Details

By default getTimestamp() gives a value up to the millisecond.

In some use cases, for example when a sequence of ids need to be generated grammatically, multiple identical values will be generated within the same millisecond.

This wrapper calls getTimestamp() with k = 1000000 to get a value up to the microsecond. This is usually enough the get unique value for example when it's called from applying a function over a list.

Value

a numeric.

Examples

uuid()

# showing what the function is trying to solve
any(duplicated(replicate(100, getTimestamp())))
any(duplicated(replicate(100, uuid())))

JavaScript Dependency

Description

Checks whether a specific dependency is already inserted in the UI with this function, and performs the insert if necessary.

Usage

with_js(package, src, script, session = shiny::getDefaultReactiveDomain())

Arguments

package

the name of the package.

src

where to find the script (see details).

script

the script to include (relative to src).

session

the session object of the Shiny server.

Details

The function is designed to be called from another function creating/updating a widget that requires JavaScript. With this, the user does not need to manage the dependency manually.

When session is NULL, the function will return without doing anything. This is useful when the function is called from ui side. The JavaScript dependency will be attached next time the function is called from server side. This is because the session$userData object cannot be updated from ui side.

Details about src can be found in htmlDependency.

Value

NULL (invisibly)

Examples

## Not run: 
with_js(package = "ktag", src = "assets", script = "js/ktag.js",
session = shiny::getDefaultReactiveDomain())

## End(Not run)