如何在R中用相同的字符串替换多个字符串 [英] How to replace multiple strings with the same in R

查看:548
本文介绍了如何在R中用相同的字符串替换多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串

vec = c('blue','red','flower','bee')

我想将一行中的不同字符串转换成相同的字符串,而不是单独地 也就是说,我可以用gsub蓝色和gsub红色使它们都拼写为"color".我怎么能在一排中做到这一点?

I want to convert different strings into the same in one line instead of seperately i.e. i could gsub blue and gsub red to make them both spell 'colour'. How can I do this in one line?

输出应为: '颜色','颜色','花','蜜蜂'

output should be: 'colour','colour','flower','bee'

推荐答案

sub("blue|red", "colour", vec)

使用"|" (包含或)在您想要替换的字词之间. 使用sub仅更改第一次出现,并使用gsub更改同一字符串中的多次出现.参见?gsub

use "|" (meening or) between the words you want to sub. use sub to change only the first occurence and gsub to change multiple occurences within the same string. See ?gsub

这篇关于如何在R中用相同的字符串替换多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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