20190506-R语言字符处理函数substr、substri
2019-05-06 本文已影响0人
天空的小白
substr
Usage
substr(x, start, stop);
提取或替换特定位置的字符,类比chartr
Example

substring
Usage
substring(text, first, last = 1000000L)
提取或替换特定位置的字符,类比chartr,默认last为很大的数
Example

第一个例子起到字符串拆分的作用(不常用)
sub
Usage
sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
在向量x中寻找特定字符(pattern),将其替换为replacement,只替换第一次匹配的字符串
Arguments
- ignore.case→若为FALSE区分大小写;若为TRUE则忽略大小写,默认为FALSE
- fixed→有特殊含义的字符(例如“.”, “\”),需要将fixed参数设为TRUE,默认为FALSE
Example
sub
gsub
Usage
gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
在向量x中寻找特定字符(pattern),将其替换为replacement,gsub()是对向量里面的每个元素进行搜素,如果发现元素里面有多个位置匹配了模式,则全部进行替换
Example

sub()与gsub()的区别
sub只替换第一次匹配的字符串,gsub会替换掉所有匹配的字符串
Example

