Skip to contents

Rename columns of a data.frame or matrix.

Usage

renameCol(x, old, new)

Arguments

x

A data.frame or matrix.

old

Character vector with names(s), or numeric vector of the indices of the column(s) you want to rename.

new

Character vector of new names.

Value

A data.frame or matrix.

Examples


x <- data.frame(old_x = 1:5, old_y = letters[1:5], old_z = LETTERS[1:5])
x
#>   old_x old_y old_z
#> 1     1     a     A
#> 2     2     b     B
#> 3     3     c     C
#> 4     4     d     D
#> 5     5     e     E
renameCol(x, c('old_y', 'old_z'), c('new_Y', 'new_Z'))
#>   old_x new_Y new_Z
#> 1     1     a     A
#> 2     2     b     B
#> 3     3     c     C
#> 4     4     d     D
#> 5     5     e     E
renameCol(x, c(2, 3), c('new_Y', 'new_Z')) # same as above
#>   old_x new_Y new_Z
#> 1     1     a     A
#> 2     2     b     B
#> 3     3     c     C
#> 4     4     d     D
#> 5     5     e     E

# Long way:
new <- c('new_Y', 'new_Z')
colnames(x)[match(c('old_y', 'old_z'), colnames(x))] <- new