替换/翻译字符串中的字符
我有一个带有字符列的数据框:
df <- data.frame(var1 = c("aabbcdefg", "aabbcdefg"))
df
# var1
# 1 aabbcdefg
# 2 aabbcdefg
我想替换几个不同的单个字符,例如从“a”到“h”,从“b”到“i”等等。目前,我多次调用 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
但是,我确信还有更优雅的解决方案。有什么想法可以继续吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要
chartr
:You want
chartr
:您可以创建
from
和to
向量:然后对
gsub
函数进行向量化:这给出:
You can create
from
andto
vectors:and then vectorialize the
gsub
function:Which gives:
如果您不想使用 Chartr 因为替换可能不止一个字符,那么另一种选择是使用 gsubfn 包中的 gsubfn (我知道这不是 gsub,而是 gsub 的扩展)。下面是一个示例:
替换也可以是一个函数,它接受匹配并返回该匹配的替换值。
If you don't want to use chartr because the substitutions may be more than one character, then another option is to use gsubfn from the gsubfn package (I know this is not gsub, but is an expansion on gsub). Here is one example:
The replacement can also be a function that would take the match and return the replacement value for that match.