目录
处理信息不可避免地要面对字符串,R提供了许多处理字符串的函数
1.计算字符串长度nchar
> nchar("hello world")
[1] 11
2.粘贴字符串paste
> paste("hello","world")
[1] "hello world"
> paste("hello","world",sep = "--")
[1] "hello--world"
3.提取字符substr
> a<-c("hello","world")
> substr(x=a,start = 2,stop = 3)
[1] "el" "or"
4.转大写toupper
> a
[1] "hello" "world"
> toupper(a)
[1] "HELLO" "WORLD"
5.转小写tolower
> a
[1] "HELLO" "WORLD"
> tolower(a)
[1] "hello" "world"
6.首字母大小写gsub
> gsub("^(\\w)","\\U\\1",tolower(a))
[1] "Uhello" "Uworld"
7.查找字符串grep
> a
[1] "hello" "world"
> grep("world",a,fixed = T)
[1] 2
8.查找字符串match
> match("world",a)
[1] 2
注意:match不支持正则表达式
9.字符串分块strsplit
> strsplit(a,"/")
[[1]]
[1] "hello"
[[2]]
[1] "world"
注意:strsplit返回的是一个列表
11.组合字符串outer
> a<-1:10
> b<-c("hello","world","you")
> outer(a,b,FUN = paste)
[,1] [,2] [,3]
[1,] "1 hello" "1 world" "1 you"
[2,] "2 hello" "2 world" "2 you"
[3,] "3 hello" "3 world" "3 you"
[4,] "4 hello" "4 world" "4 you"
[5,] "5 hello" "5 world" "5 you"
[6,] "6 hello" "6 world" "6 you"
[7,] "7 hello" "7 world" "7 you"
[8,] "8 hello" "8 world" "8 you"
[9,] "9 hello" "9 world" "9 you"
[10,] "10 hello" "10 world" "10 you"