Replace characters using gsub, how to create a function?

jrara picture jrara · Aug 5, 2011 · Viewed 34.6k times · Source

I'm trying to replace characters in a data.frame. I have a solution for this

> df <- data.frame(var1 = c("aabbcdefg", "aabbcdefg"))
> df
       var1
1 aabbcdefg
2 aabbcdefg
> df$var1 <- gsub("a", "h", df$var1)
> df$var1 <- gsub("b", "i", df$var1)
> df$var1 <- gsub("c", "j", df$var1)
> df$var1 <- gsub("d", "k", df$var1)
> df$var1 <- gsub("e", "l", df$var1)
> df$var1 <- gsub("f", "m", df$var1)
> df
       var1
1 hhiijklmg
2 hhiijklmg
> 

but I would like to avoid using several gsub calls, it would be much nicer to produce a function to do this at once?

Any ideas ho to proceed?

Answer

Marek picture Marek · Aug 5, 2011

You want chartr:

df$var1 <- chartr("abcdef", "hijklm", df$var1)
df
#        var1
# 1 hhiijklmg
# 2 hhiijklmg