coffeinjunky
coffeinjunky

Reputation: 11514

Replace many different characters "one by one"? R

Every now and then I encounter the following problem: I want to replace several characters in an object with "nicer" characters. For instance, I want to change cryptic variable names to readable ones in tables for publication, or I want to change names of variables in a dataframe. I typically end up implementing a copy & paste solution. For instance,

 dat <- mtcars
 names(dat) <- gsub("mpg", "Miles", names(dat))
 names(dat) <- gsub("cyl", "Cylinder", names(dat))
 ... etc

The pattern here is always the same: take an object with names (here it is the names of variables in a dataframe, but it could just be characters in any vector) and replace some elements with others, and repeat.

I am looking for way to do this more efficiently. For instance, I have been thinking of sth along these lines:

 from <- c("mpg", "cyl")
 to   <- c("Miles", "Cylinder")
 names(dat) <- magic.function(from, to, names(dat))
 # ok, does not look like a big improvement, unless you think of 20 or 30 names...

I am looking for something that achieves the same as the following for-loop:

 for(i in seq_along(from)){
      names(dat) <- gsub(from[i], to[i], names(dat))
 }

but in a more elegant (i.e. no loop) way. While it is easy to implement such a function myself, there probably is a built in function available doing this already, either in base or in some packages. Does anyone know about such a function?

Upvotes: 0

Views: 61

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

I would suggest the "stringi" package for something like this:

library(stringi)
stri_replace_all_fixed(names(dat), from, to, vectorize_all = FALSE)
#  [1] "Miles"    "Cylinder" "disp"     "hp"       "drat"     "wt"      
#  [7] "qsec"     "vs"       "am"       "gear"     "carb"    

Upvotes: 3

Related Questions