字符处理函数用于处理文本型数据。
- nchar()
- substr()
- grep()
- sub()
- strsplit()
- paste()
- toupper()
- tolower()
描述
函数 | 描述 |
---|---|
nchar(x) | 计算x中字符数量 |
substr(x,start,stop) | 提取或替换一个字符向量中的子串 |
grep(pattern,x,ignore.case=TRUE,fixed) | 在x中搜索某种模式。fixed=FALSE,pattern为正则表达式。fixed=TRUE,pattern为一个文本字符串。返回值为匹配的下标 |
sub(pattern,replacement,x,ignore.case=FALSE,fixed=FALSE) | 在x中搜索pattern,并以文本replacement将其替换。fixed参数同grep |
strsplit(x,split,fixed=FALSE) | 在split处分割字符向量x中的元素 |
paste(-,sep=’’) | 连接字符串,分隔符为sep |
toupper(x) | 大写转换 |
tolower(x) | 小写转换 |
示例
#nchar()
a <- c('an','cd','dafsaf')
#查看a中各字符长度
nchar(a)
[1] 2 2 6
#substr()
b <- 'hfdhkjdshf'
#提取b中第2到5位
substr(b,2,5)
[1] "fdhk"
#grep()
c <- c('A','B','V')
#在c中匹配含有字符A的元素。
grep('A',c)
[1] 1
#sub()
d <- 'my name is Bob'
#在d中匹配my将其替换为his
sub('my','his',d,fixed = TRUE)
[1] "his name is Bob"
#strsplit()
e <- '哪里不会点哪里'
#将e以‘会’分割
strsplit(e,'会',fixed=TRUE)
[[1]]
[1] "哪里不" "点哪里"
#paste()
#连接x与1:3
paste('x',1:3,sep ='' )
[1] "x1" "x2" "x3"
#toupper()
toupper('myname')
[1] "MYNAME"
#tolower()
tolower('HISNAME')
[1] "hisname"