在R中的一个gsub()或chartr()语句中替换多个字符串? [英] Replace multiple strings in one gsub() or chartr() statement in R?

查看:60
本文介绍了在R中的一个gsub()或chartr()语句中替换多个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字母[a-z],空格[]和撇号[']的字符串变量,例如. x <- "a'b c" 我想用空格[]替换撇号['],并用下划线[_]替换空格[].

I have a string variable containing alphabet[a-z], space[ ], and apostrophe['],eg. x <- "a'b c" I want to replace apostrophe['] with blank[], and replace space[ ] with underscore[_].

x <- gsub("'", "", x)
x <- gsub(" ", "_", x)

它绝对有效,但是当我有很多情况时,代码变得丑陋.因此,我想使用chartr(),但是chartr()不能处理空白,例如.

It works absolutely, but when I have a lot of condition, the code becomes ugly. Therefore, I want to use chartr(), but chartr() can't deal with blank, eg.

x <- chartr("' ", "_", x) 
#Error in chartr("' ", "_", "a'b c") : 'old' is longer than 'new'

有什么办法可以解决这个问题?谢谢!

Is there any way to solve this problem? thanks!

推荐答案

您可以使用gsubfn

library(gsubfn)
gsubfn(".", list("'" = "", " " = "_"), x)
# [1] "ab_c"

类似地,我们也可以使用mgsub,它允许用多种模式进行多次替换进行搜索

Similarly, we can also use mgsub which allows multiple replacement with multiple pattern to search

mgsub::mgsub(x, c("'", " "), c("", "_"))
#[1] "ab_c"

这篇关于在R中的一个gsub()或chartr()语句中替换多个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆