Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

r - Replace / translate characters in a string

I have a data frame with a character column:

df <- data.frame(var1 = c("aabbcdefg", "aabbcdefg"))
df
#        var1
# 1 aabbcdefg
# 2 aabbcdefg

I want to replace several different individual characters, e.g. from "a" to "h", from "b" to "i" and so on. Currently I use several calls to gsub:

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

However, I'm sure there are more elegant solutions. Any ideas ho to proceed?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want chartr:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...