> 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()也是對向量里每個元素進行搜索,但它僅僅知道元素是否匹配了模式(並返回該元素在向量中的下標),但具體元素中匹配了多少次卻無法知道。在這里僅僅是為了說明這兩者的區別,這在實際中可能不會用到。