zoukankan      html  css  js  c++  java
  • R语言 sub与gsub函数的区别

    > 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()也是对向量里每个元素进行搜索,但它仅仅知道元素是否匹配了模式(并返回该元素在向量中的下标),但具体元素中匹配了多少次却无法知道。在这里仅仅是为了说明这两者的区别,这在实际中可能不会用到。

  • 相关阅读:
    学习Python之路
    基本数据类型
    pthon之变量
    函数、参数、局部函数and函数内变量修改、嵌套函数
    文件操作M2
    文件IO操作二
    文件I/O操作
    字符编码
    数据类型之集合,数据类型总结
    数据类型之列表和元组
  • 原文地址:https://www.cnblogs.com/nkwy2012/p/8625063.html
Copyright © 2011-2022 走看看