创建字符串是通过一对双引号“”或使用函数as.character()来完成的。
> string<-c("one","two","three")
> string
[1] "one" "two" "three"
> as.character(1:3)
[1] "1" "2" "3"
函数noquote()可用来抑制R的输出结果中双引号的显示。
> noquote(string)
[1] one two three
函数sQuote()和dQuote用来显示不同样式的引号
> sQuote(string)
[1] "‘one’" "‘two’" "‘three’"
> dQuote(string)
[1] "“one”" "“two”" "“three”"
函数nchar()计算一个字符串中字符的数目,它可对一个字符串向量进行操作
> string1<-c("a","ab","B","bba","one","!@","brute")
> nchar(string1)
[1] 1 2 1 3 3 2 5
> string1[nchar(string1)>2]
[1] "bba" "one" "brute"
命令letters和LETTERS分别返回26个小写和大写的拉丁字母
> letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"
[19] "s" "t" "u" "v" "w" "x" "y" "z"
> LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R"
[19] "S" "T" "U" "V" "W" "X" "Y" "Z"
函数paste()用于连接若干个字符串。
> string2<-c("e","D")
> paste(string1,string2)
[1] "a e" "ab D" "B e" "bba D" "one e" "!@ D" "brute e"
> paste(string1,string2,sep="-")
[1] "a-e" "ab-D" "B-e" "bba-D" "one-e" "!@-D" "brute-e"
> paste(string1,string2,collapse = "",sep="")##collapse可用来实现将字符串向量中的元素连接成 单个字符串
[1] "aeabDBebbaDonee!@Dbrutee"
函数strstring()用来从一个字符串中提取子字符串
> subsring("abcdef",first=1:3,last=2:4)
Error in subsring("abcdef", first = 1:3, last = 2:4) :
could not find function "subsring"
> substring("abcdef",first=1:3,last=2:4)
[1] "ab" "bc" "cd"
> ?substring
> substring("abcdef",first=1,last=5)
[1] "abcde"
函数strsplit()用于分裂一个字符串
> strsplit(c("05 jan","06 feb"),split=" ")
[[1]]
[1] "05" "jan"
[[2]]
[1] "06" "feb"
函数grep()用来在字符串向量中搜寻某一种模式,他返回字符串向量中包含这一模式的元素的位置索引。
> grep("i",c("pierre","benoit","rems"))
[1] 1 2
函数gsub()将字符串向量中所有元素中具有某一模式的部分以另外一个字符(串)进行替换。
> gsub("i","L",c("pierre","benoit","rems"))
[1] "pLerre" "benoLt" "rems"
函数sub()仅替换第一个具有特定模式的字符串中的那一部分。
> sub("r","L",c("pierre","benoit","rems"))
[1] "pieLre" "benoit" "Lems"
函数tolower()和toupper()可分别用来将一个字符串强制变为小写或大写形式。
> tolower("loWER")
[1] "lower"
> toupper("UPper")
[1] "UPPER"