dt_add_to_col_names: Add string to all column names in a data.table

dt_add_to_col_namesR Documentation

Add string to all column names in a data.table

Description

Takes a data.table and a string. The supplied string will be added to end of the each column's name. If prefix is TRUE, the string is added to the beginning, instead.

Usage

dt_add_to_col_names(
  DT,
  astring,
  prefix = FALSE,
  exclude = NULL,
  include = NULL,
  fix.duplicates = FALSE
)

Arguments

DT

A data.table

astring

A string to add to each column name

prefix

A logical indicating whether the string should be added to the beginning of each column name, instead of the end. (default is FALSE)

exclude

A quoted vector or column names to exclude from renaming. Cannot co-exist with include

include

A quoted vector or column names. Changes names of only these columns. Cannot co-exist with exclude

fix.duplicates

A logical indicating whether to, if after the suffix/prefixes are added to the selected column names, correct those duplicate column names by making them unique. If FALSE (default), if any of the column names are duplicated, an error is raised and the new names are not set. If TRUE, all the column names are made unique, potentially renaming excluded column names that were not supposed to be changed.

Value

Returns data.table with string appended or prefixed to all selected column names.

Examples

DT <- as.data.table(iris)

dt_add_to_col_names(DT, "_post")
names(DT)
# [1] "Sepal.Length_post" "Sepal.Width_post"  "Petal.Length_post"
# [4] "Petal.Width_post"  "Species_post"

 DT <- as.data.table(iris)
dt_add_to_col_names(DT, "pre_", prefix=TRUE)
names(DT)
# [1] "pre_Sepal.Length" "pre_Sepal.Width"  "pre_Petal.Length" "pre_Petal.Width"
# [5] "pre_Species"

DT <- as.data.table(iris)
dt_add_to_col_names(DT, "_post", exclude="Species")
names(DT)
# [1] "Sepal.Length_post" "Sepal.Width_post"  "Petal.Length_post"
# [4] "Petal.Width_post"  "Species"


libbib documentation built on Nov. 10, 2022, 6:16 p.m.