在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
> text <- c("we are the world", "we are the children")
> sub("w", "W", text)
[1] "We are the world" "We are the children"
> sub("W","w",text)
[1] "we are the world" "we are the children"
> gsub("W","w",text)
[1] "we are the world" "we are the children"
> gsub("w","W",text)
[1] "We are the World" "We are the children"
> sub(" ", "", "abc def ghi")
[1] "abcdef ghi"
> ## [1] "abcdef ghi"
> gsub(" ", "", "abc def ghi")
[1] "abcdefghi"
> ## [1] "abcdefghi"
从上面的输出结果可以看出,sub()和gsub()的区别在于,前者只替换第一次匹配的字符串,而后者会替换掉所有匹配的字符串。
从上面的输出结果可以看出,sub()和gsub()的区别在于,前者只替换第一次匹配的字串(请注意输出结果中world的首字母),而后者会替换掉所有匹配的字串。
注意:gsub()是对向量里面的每个元素进行搜素,如果发现元素里面有多个位置匹配了模式,则全部进行替换,而grep()也是对向量里每个元素进行搜索,但它仅仅知道元素是否匹配了模式(并返回该元素在向量中的下标),但具体元素中匹配了多少次却无法知道。在这里仅仅是为了说明这两者的区别,这在实际中可能不会用到。 |
请发表评论