df.rename: Rename Columns in a Matrix or Variables in a Data Frame

View source: R/df.rename.R

df.renameR Documentation

Rename Columns in a Matrix or Variables in a Data Frame

Description

This function renames columns in a matrix or variables in a data frame by (1) using old_name = new_name, by using the functions toupper, tolower, sub, and gsub, or (3) by specifying a character vector indicating the column(s) or variable(s) to be renamed (argument from) and a character vector indicating the corresponding replacement values (argument to).

Usage

df.rename(data, ..., from, to, check = TRUE)

Arguments

data

a matrix or data frame.

...

old_name = new_name when from = NULL and to = NULL, or one of the functions toupper, tolower, sub, and gsub. Note that a tilde (~) needs to be specified before when using a function, e.g., ~toupper or ~gsub("_", ".").

from

a character vector indicating the column(s) or variable(s) to be renamed.

to

a character vector indicating the corresponding replacement values for the column(s) or variable(s) specified in the argument name.

check

logical: if TRUE (default), argument specification is checked.

Value

Returns the matrix or data frame data with renamed columns or variables.

Author(s)

Takuya Yanagida

See Also

df.check, df.duplicated, df.unique, df.head, df.tail, df.long, df.wide, df.merge, df.move, df.rbind, df.round, df.sort, df.subset

Examples

#————————————————————————————————————————————————————————————————————————————
# Rename using variable names

# Example 1a: Rename 'cyl' in 'mtcars' to 'cylinder' using 'old_name = new_name'
df.rename(mtcars, cyl = cylinder)

# Example 1b: Rename 'cyl' in 'mtcars' to 'cylinder' using 'from' and 'to'
df.rename(mtcars, from = "cyl", to = "cylinder")

# Example 2a: Rename 'cyl' and 'wt' in 'mtcars' to 'cylinder' and 'weight'
# using 'old_name = new_name'
df.rename(mtcars, cyl = cylinder, wt = weight)

# Example 2b: Rename 'cyl' and 'wt' in 'mtcars' to 'cylinder' and 'weight'
# using using 'from' and 'to'
df.rename(mtcars, from = c("cyl", "wt"), to = c("cylinder", "weight"))

#————————————————————————————————————————————————————————————————————————————
# Rename using functions

# Example 3: Convert all variable names to lowercase
df.rename(iris, ~tolower)

# Example 4: Replace all '.' with '_'
# Note, the argument fixed is set to TRUE by default.
df.rename(iris, ~gsub(".", "_"))

# Example 5: Replace all 'S' with 'P'
df.rename(iris, ~gsub("S", "P"))

# Example 6: Replace all 'S' with 'P', ignore case during matching
df.rename(iris, ~gsub("S", "P", ignore.case = TRUE))

misty documentation built on Nov. 24, 2026, 5:06 p.m.

Related to df.rename in misty...