《R语言经典示例》学习笔记(五)

来源:互联网 发布:乔巴姆装甲 知乎 编辑:程序博客网 时间:2024/05/17 22:08

字符串

获取字符串长度

  • nchar(“”)
    函数nchar以一个字符串为参数,返回这个字符串中的字符数。不同于length()函数,length()函数返回一个向量的长度。
> nchar("xuptduxu")[1] 8> a<-c("happy","birthday","to","you")> nchar(a)[1] 5 8 2 3> length("xuptduxu")[1] 1

连接字符串

  • paste()函数
> paste("happy","birthday","to","you!")[1] "happy birthday to you!"> paste("happy","birthday","to","you!",sep = "")[1] "happybirthdaytoyou!"> paste("happy","birthday","to","you!",sep = "-")[1] "happy-birthday-to-you!"

提取子串

  • substr(string,start,end)函数:string原始字符串;提取开始于start,结束于end的子串
> substr("xuptduxu",5,8)[1] "duxu"> ss<-c("Moe","Larry","Curly")> substr(ss,1,3)[1] "Moe" "Lar" "Cur"> cities<-c("New York, NY","Los Angeles, CA","Peoria, IL")> substr(cities,nchar(cities)-1,nchar(cities))[1] "NY" "CA" "IL"

根据分隔符分割字符串

  • strsplit(string,delimiter)函数:将一个字符串分割为多个子串,子串之间用分隔符分开;delimiter可以是一个简单的字符串或者一个正则表达式;该函数返回一个列表
> path<-"/home/mike/data/trials.csv"> strsplit(path,"/")[[1]][1] ""      "home"     "mike"     "data"     "trials.csv"

替代子串

  • sub(old,new,string)函数:替代字符串的第一个子串实例
  • gsub(old,new,string)函数:替代字符串的所有子串实例
> s<-"Curly is the smart one.Curly is funny,too."> sub("Curly","Moe",s)[1] "Moe is the smart one.Curly is funny,too."> gsub("Curly","Moe",s)[1] "Moe is the smart one.Moe is funny,too."> sub(" and SAS.","","You need R and SAS.")[1] "You need R"

生成字符串的所有成对组合

  • outer(strings1,strings2,paste,sep=”“)函数:结果是一个矩阵
> year<-c("2000","2001","2002","2003")> month<-c("1","2","3","4","5","6")> outer(year,month,paste,sep="-")     [,1]     [,2]     [,3]     [,4]     [,5]     [,6]    [1,] "2000-1" "2000-2" "2000-3" "2000-4" "2000-5" "2000-6"[2,] "2001-1" "2001-2" "2001-3" "2001-4" "2001-5" "2001-6"[3,] "2002-1" "2002-2" "2002-3" "2002-4" "2002-5" "2002-6"[4,] "2003-1" "2003-2" "2003-3" "2003-4" "2003-5" "2003-6"

得到当前日期

  • Sys.Date()函数
> Sys.Date()[1] "2016-05-20"
0 0
原创粉丝点击