字符處理函數用於處理文本型數據。
- 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"