Skip to contents

[Experimental]

This function fixes the column names of a given object so that all words are spaced by a specified delimiter, and any special characters are replaced according to a substitution map.

Usage

fixColnames(
  object,
  invalidRegex = joinRegex(" ", "\\)", "\\(", "\\.", "/"),
  spacing = "_",
  subMap = NULL,
  .subMap = list(`%+` = "pct", `\\$+` = "dollars", `\\++` = "plus", `-+` = "minus",
    `\\*+` = "star", `#+` = "cnt", `&+` = "and", `@+` = "at"),
  unique = FALSE
)

Arguments

object

A data frame or matrix.

invalidRegex

A character string containing a regex pattern for invalid characters to replace. Default is "( )|(\()|(\))|(\.)|(/)".

spacing

A character string to replace invalid characters with. Default is "_".

subMap

A named list where the names are regular expressions and the values are the replacement strings. These substitutions are applied before .subMap.

.subMap

A named list where the names are regular expressions and the values are the replacement strings. These substitutions are applied after subMap. Default is list("\+" = "plus").

unique

A logical indicating whether to ensure unique column names by appending a suffix if necessary. Default is FALSE.

Value

The data frame or matrix with fixed column names.

Examples

# Fix column names of a data frame
df <- data.frame(
    `A (1)` = c(1, 2, 3), `B/C` = c(4, 5, 6), `D+E` = c(7, 8, 9)
)
fixColnames(df)
#>   a_1 b_c d_e
#> 1   1   4   7
#> 2   2   5   8
#> 3   3   6   9