kwb.utils R Package

website·Indexed 30 days ago

https://kwb-r.github.io/kwb.utils/index.html

A collection of utility functions for the R programming language, providing tools for path manipulation, vector and list conversions, matrix operations, and system-level helpers such as object size calculation and batch file execution.

Tokens
63.6K
Snippets
391
Records
607
Agent score
75%

What's inside kwb.utils

  1. Overview of kwb.utils package

    The kwb.utils R package provides a collection of utility functions designed to help developers write cleaner, safer, and less redundant code. The package includes a wide variety of helpers for data manipulation, string processing, and system operations.
  2. Split a data frame into two using unmerge

    The unmerge(z, by) function splits a data frame z into two data frames, x and y, such that merge(x, y) results in the original data frame z.

    It identifies columns that are constant within groups defined by the by argument. Columns that are constant for every row in a group are placed in data frame x, while all other columns are placed in data frame y. Both resulting data frames will contain the columns specified in by to allow for future merging.

    # Example: Split data by 'name'
    # Columns constant for each name (age, height) go to $x
    # Varying columns (subject, year, mark) go to $y
    result <- unmerge(z, by = "name")
    
    # To reconstruct the original data frame:
    reconstructed <- merge(result$x, result$y)
  3. Implement a custom list function for listToDepth

    When providing a custom function FUN to listToDepth for retrieving element details, the function must adhere to the following requirements:

    1. It must be able to handle cases where no path is provided (empty input).
    2. It must return a data frame containing at least the columns file and isdir.
    3. It must return empty records (a data frame with the required columns but no rows) when called with an empty character vector.
    # Example of a compatible list function using kwb.utils:::listFiles
    FUN <- kwb.utils:::listFiles
    
    # The function should return a data frame with 'file' and 'isdir' columns
    # even when called without arguments
    FUN()
  4. Manage placeholders and overrides in resolve()

    You can define or override placeholders 'on-the-fly' by passing named arguments to the resolve() function. These named arguments act as a dictionary that takes precedence or fills in missing values during the resolution process.
    # Set an undefined placeholder on-the-fly
    resolve("file.out", dictionary, extension = "pdf")
    
    # Override an existing placeholder on-the-fly
    resolve("dir.project", dictionary, project = "new_project")
  5. Locate CSV headers using readCsvInputFile

    You can specify how the function finds the header row using two primary methods:

    1. By Row Index: Set headerRow to the specific row number containing the captions.
    2. By Pattern: Set headerPattern to a regex pattern. If headerPattern is provided, headerRow is ignored, and the function searches for the pattern within the first maxRowToLookForHeader rows (default is 10).
  6. Example: Convert a matrix to a data frame with custom names

    This example demonstrates how to convert a matrix with specific dimensions and names into a long-format data frame, including how to override the default column names.
    # Create a matrix with 3 rows and 4 columns
    m1 <- matrix(1:12, nrow = 3, dimnames = list(NULL, letters[1:4]))
    
    # Basic conversion (defaults to row, column, value)
    matrixToDataFrame(x = m1)
    
    # Change column order so column coordinate comes first
    matrixToDataFrame(x = m1, row_first = FALSE)
    
    # Provide custom names for all three columns
    matrixToDataFrame(x = m1, "myrow", "mycol", "myval")
  7. Recursively list elements using listToDepth

    The listToDepth function lists elements recursively starting from a given path. It allows control over the recursion depth and the level of detail returned for each element. The function relies on a provider function (FUN) to perform the actual listing of a single directory or path.
    listToDepth(
      path,
      max_depth = 0L,
      full_info = FALSE,
      FUN = listFiles,
      ...
    )
  8. Example: Write text to a temporary file with custom debug labels

    This example demonstrates how to define a character vector, write it to a temporary file, and use the type argument to make the debug output more informative.
    # Define text to be written to file
    x <- c("Hello", "world")
    
    # Write text to a temporary file and capture the file path
    file <- writeText(x, tempfile(fileext = ".txt"))
    # Output: Writing '/path/to/tempfile.txt' ... ok.
    
    # Write again with a custom type for a more informative debug message
    writeText(x, file, type = "welcome file")
    # Output: Writing welcome file '/path/to/tempfile.txt' ... ok.
  9. Configure hsQuoteChr arguments

    The hsQuoteChr function accepts the following arguments:

    • x: A vector or list of character strings to be quoted.
    • qchar: The character used for quoting. Defaults to a single quote (').
    • escapeMethod: Determines how to treat the quoting character if it occurs within the string. Must be one of: `
  10. Change the format of a CSV file using convertCsvFile

    The convertCsvFile function allows you to modify the format of a CSV file (e.g., changing the column delimiter or decimal character). It reads the input file using read.table and writes the modified version using write.table.

    Arguments that are common to both read.table and write.table are provided as pairs: <argument>_in for the input file and <argument>_out for the output file. All other arguments for those two base R functions are supported via the ... parameter.

    # Example: Convert column separator from default to ';' and decimal character to ','
    csv_out <- convertCsvFile(
      file_in = "input.csv", 
      sep_out = ";", 
      dec_out = ","
    )
  11. Generate reproducible samples using reproducibleSample

    The reproducibleSample function wraps a sampling function (defaulting to sample) and captures the state of the random seed. It stores the required seed values in the random_seed attribute of the returned vector. To reproduce the exact same sample in a subsequent call, pass this captured seed vector back into the random_seed argument.
    # 1. Take an initial sample
    x <- reproducibleSample(1:100, 10)
    
    # 2. Extract the seed vector from the result attribute
    seed_val <- attr(x, "random_seed")
    
    # 3. Use that seed to generate the identical sample again
    y <- reproducibleSample(1:100, 10, random_seed = seed_val)
    
    # Verify results are identical
    identical(x, y) # Returns TRUE
  12. Reorder strings to group matching prefixes using pairwise()

    The pairwise() function reorders a character vector x so that strings starting with the same characters appear next to each other. You can control grouping either by providing a specific vector of prefixes to look for via the starts argument or by specifying a split character/pattern that the function uses to automatically determine the prefixes.
    x <- c("a.1", "b_hi", "c", "a.2", "d", "b_bye")
    
    # 1. Explicitly define the prefixes to group by
    pairwise(x, starts = c("a.", "b_"))
    #> [1] "a.1"   "a.2"   "b_hi"  "b_bye" "c"     "d"
    
    # 2. Use a split character (default is "_") to determine prefixes
    pairwise(x, split = "_")
    #> [1] "a.1"   "b_hi"  "b_bye" "c"     "a.2"   "d"
    
    # 3. Use a regex pattern for the split (e.g., to split by dot or underscore)
    pairwise(x, split = "[._]")
    #> [1] "a.1"   "a.2"   "b_hi"  "b_bye" "c"     "d"