Johannes Kutsam
Johannes Kutsam

Reputation: 240

How to do pairwise replacement of strings efficiently

I have a list of coefficient names and I want to replace the technical terms with nicer labels. A function call would look like this

replace.pairwise(list("coef1","coef2"),
                 coef1="price",coef2="eventdummy", coef3="income")

and should return

"price"      "eventdummy"

Upvotes: 2

Views: 190

Answers (2)

flodel
flodel

Reputation: 89097

It is quite easy. Store your translations in a named vector:

translations <- c(coef1 = "price", coef2 = "eventdummy", coef3 = "income")

Then use [:

vector.of.strings <- c("coef1","coef2")

translations[vector.of.strings]
#        coef1        coef2 
#      "price" "event dummy"

As you can see, the output is also a named vector. If the names are a problem for you, you can just do unname(translations[vector.of.strings]).

Also if your original names are in a list like in your example, you already know about unlist:

translations[unlist(list.of.strings)]

Important: everything above works well if all of your original names have a replacement. If it is not the case and you only want to modify those names for which there is a replacement, you can do:

ifelse(is.na(translations[vector.of.strings]),
       vector.of.strings,
       translations[vector.of.strings])

Upvotes: 3

Johannes Kutsam
Johannes Kutsam

Reputation: 240

The function that worked for me was

replace.pairwise=function(listofstrings,...){
  ss=c(unlist(listofstrings))
  pairs=list(...)

  for(s in 1:length(ss)){
    for(p in 1:length(pairs)){
      ss[s]=gsub(names(pairs)[p],pairs[p],ss[s])
    }  
  }
  ss
}

I am sure it is not the most efficient way, but it works. I wonder whether I have again just programmed something that is already hidden in one of the many packages in R...

Upvotes: 2

Related Questions