colnamesReplace.RdA convenience function to alter column names. Can be called from code cleanup in the variable key system.
colnamesReplace(
dat,
newnames,
oldnames = NULL,
...,
lowercase = FALSE,
verbose = FALSE
)a data frame
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.
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.
Default FALSE. Should all column names be converted to lower case.
Default FALSE. Want diagnostic output about column name changes?
a data frame
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)
#> colnamesReplace Diagnostic: These names replacements are requested:
#> [1] "oldnames" "newnames"
#> oldnames newnames
#> x4 "x4" "GLOPPY"
#> USA "USA" "Interesting"
#> These names were actually replaced:
colnames(mydf2)
#> [1] "x5" "GLOPPY" "x3" "x2" "x1" "x11" "x12" "x13"
head(mydf3 <- colnamesReplace(mydf, newnames = c(x11 = "x12", x12 = "x13", x13 = "x20")))
#> x5 x4 x3 x2 x1 x12 x13 x20
#> 1 -0.1308295 -0.6267455 0.1946483 v greg 7 18 33
#> 2 -0.6777994 0.9054334 -0.4713774 e chris 7 18 33
#> 3 0.1435791 0.2562883 0.1158323 i bobby 7 18 33
#> 4 -0.4879708 -0.3852887 -0.1471906 k marsha 7 18 33
#> 5 -0.1845969 1.0947934 -0.4266429 i bobby 7 18 33
#> 6 0.5976032 1.0255002 -0.1697781 d cindy 7 18 33
head(mydf4 <- colnamesReplace(mydf, newnames = c(x12 = "x11", x11 = "x99", x13 = "x20")))
#> x5 x4 x3 x2 x1 x99 x11 x20
#> 1 -0.1308295 -0.6267455 0.1946483 v greg 7 18 33
#> 2 -0.6777994 0.9054334 -0.4713774 e chris 7 18 33
#> 3 0.1435791 0.2562883 0.1158323 i bobby 7 18 33
#> 4 -0.4879708 -0.3852887 -0.1471906 k marsha 7 18 33
#> 5 -0.1845969 1.0947934 -0.4266429 i bobby 7 18 33
#> 6 0.5976032 1.0255002 -0.1697781 d cindy 7 18 33