as.character(x) 将其他类型的对象想转换为字符型
> x<-c(1:5) #数值型
> x
[1] 1 2 3 4 5
> as.character(x) #转换后变为字符型
[1] "1" "2" "3" "4" "5"
is.character(x)判断x是否为字符型
> is.character(x)
[1] FALSE
nchar()函数,提取字符向量中字符串的个数
> y<-c("wo","shi","yi","zhi","ke","yan","gou")
> y
[1] "wo" "shi" "yi" "zhi" "ke" "yan" "gou"
> nchar(y)
[1] 2 3 2 3 2 3 3
substr()函数或substring()函数,提取或替换字符型向量的部分子串
#(1)substr(x,start,stop)。
> substr(y,2,4) #每个分量分别取2:4的字符
[1] "o" "hi" "i" "hi" "e" "an" "ou"
> substr("abcdef",2,4) #取第2到4个字符串
[1] "bcd"
#(2)substring(text,first,last)
> substring("abcdef",1:4,1:4) #可以获取单个字符
[1] "a" "b" "c" "d"
> substring("abcdef",1:4,4) #字符数逐渐减少
[1] "abcd" "bcd" "cd" "d"
strsplit()函数,将字符串分解,返回格式为列表格式
strsplit(x, split), split为分隔的符号,字母等
> y<-c("wo shi yi zhi ke yan gou")
> y
[1] "wo shi yi zhi ke yan gou"
> strsplit(y,split=" ")
[[1]]
[1] "wo" "shi" "yi" "zhi" "ke" "yan" "gou"
> unlist(strsplit(y,split=" ")) #取消列表功能
[1] "wo" "shi" "yi" "zhi" "ke" "yan" "gou"
> strsplit(y,split="i")
[[1]]
[1] "wo sh" " y" " zh" " ke yan gou"
paste()或paste0()函数,将多个对象连接在一块构成一个对象
paste(x,y,z,sep=" ") sep为分隔符,默认为空格
> paste("wo","shi")
[1] "wo shi"
> paste("wo","shi",sep="/")
[1] "wo/shi"
paste0(x,y),直接将对象连接,中间无分隔符,等同于paste(x,y,sep="")
> paste0("wo","shi")
[1] "woshi"
> paste("wo","shi",sep="")
[1] "woshi"
> x<-"file"
> y<-c(1:4)
> paste(x,y,sep=".")
[1] "file.1" "file.2" "file.3" "file.4"
noquote()函数,去掉字符型向量中的引号
> y<-c("wo","shi","yi","zhi","ke","yan","gou")
> noquote(y)
[1] wo shi yi zhi ke yan gou
字符串大小写转换
toupper,转化为大写字母
tolower,转化为小写字母
> toupper(y)
[1] "WO" "SHI" "YI" "ZHI" "KE" "YAN" "GOU"
> tolower("WOSHIYIZHIKEYANGOU")
[1] "woshiyizhikeyangou"
网友评论