Learn R Programming

misty (version 0.7.1)

df.rename: 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)

Value

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

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 string or character vector indicating the column(s) or variable(s) to be renamed.

to

a character string or 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.

Author

Takuya Yanagida takuya.yanagida@univie.ac.at

See Also

df.duplicated, df.merge, df.move, df.rbind, df.sort, df.subset

Examples

Run this code
#----------------------------------------------------------------------------
# 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))

Run the code above in your browser using DataLab