> 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()的区别在于,前者只替换第一次匹配的字符串,而后者会替换掉所有匹配的字符串。
与之相似的还有grep函数,但grep函数返回的是下标位置。