Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

colnamesReplace

Replace column names with new names from a named vector


Description

A convenience function to alter column names. Can be called from code cleanup in the variable key system.

Usage

colnamesReplace(dat, newnames, oldnames = NULL, ..., lowercase = FALSE,
  verbose = FALSE)

Arguments

dat

a data frame

newnames

Can be a named vector of the form c(oldname1 = "newname1", oldname2 = "newname") or it may be simply c("newname1", "newname2") to correspond with the oldname vector.

oldnames

Optional. If supplied, must be same length as newnames.

...

Additional arguments that will be passed to R's gsub function, which is used term-by-term inside this function.

lowercase

Default FALSE. Should all column names be converted to lower case.

verbose

Default FALSE. Want diagnostic output about column name changes?

Value

a data frame

Author(s)

Paul Johnson <pauljohn@ku.edu>

Examples

set.seed(234234)
N <- 200
mydf <- data.frame(x5 = rnorm(N), x4 = rnorm(N), x3 = rnorm(N),
                   x2 = letters[sample(1:24, 200, replace = TRUE)],
                   x1 = factor(sample(c("cindy", "bobby", "marsha",
                                        "greg", "chris"), 200, replace = TRUE)),
                   x11 = 7,
                   x12 = 18,
                   x13 = 33,
                   stringsAsFactors = FALSE)
mydf2 <- colnamesReplace(mydf, newnames = c("x4" = "GLOPPY"))
mydf2 <- colnamesReplace(mydf, newnames = c("x4" = "GLOPPY", "USA" = "Interesting"), verbose = TRUE)
colnames(mydf2)
head(mydf3 <- colnamesReplace(mydf, newnames = c(x11 = "x12", x12 = "x13", x13 = "x20")))
head(mydf4 <- colnamesReplace(mydf, newnames = c(x12 = "x11", x11 = "x99", x13 = "x20")))

kutils

Project Management Tools

v1.70
GPL-2
Authors
Paul Johnson [aut, cre], Benjamin Kite [aut], Charles Redmon [aut], Jared Harpole [ctb], Kenna Whitley [ctb], Po-Yi Chen [ctb], Shadi Pirhosseinloo [ctb]
Initial release
2020-04-28

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.