认真聊一聊R语言中的paste/paste0函数
欢迎来到医科研,这里是白介素2的读书笔记,跟我一起聊临床与科研的故事, 生物医学数据挖掘,R语言,TCGA、GEO数据挖掘。
聊一聊引无数英雄竞折腰的 paste函数
来,我们将镜头推进,仔细的研究一下paste函数
paste函数可用于字符串连接
1?paste# 看看文档大概了解下
2## starting httpd help server ... done
我们简单举个例子
1paste("a","b") #能连接a b
2## [1] "a b"
3paste("a","b","c")
4## [1] "a b c"
5#设置分隔符
6paste("a","b",sep = "=")##注意到用等号分隔了
7## [1] "a=b"
8#连接多个元素
9paste("a",1:5,sep = "")#会自动每个元素与a相连
10## [1] "a1" "a2" "a3" "a4" "a5"
11paste("a",1:5,".pdf", sep = "")#比如想批量输出文件名
12## [1] "a1.pdf" "a2.pdf" "a3.pdf" "a4.pdf" "a5.pdf"
collapse参数,谢益辉大佬说这个参数引无数英雄竞折腰啊,大家只会sep
1paste("a",1,collapse = "+")##注意到了吧,collapse没用上
2## [1] "a 1"
3paste(c("a","b","c"),collapse = "+") #这样就很容易理解了,collapse折叠起了元素
4## [1] "a+b+c"
5# 再来更明显的举例
6paste("a",1:5,sep = "")##先在元素间连接
7## [1] "a1" "a2" "a3" "a4" "a5"
8#然后折叠
9paste("a",1:5,sep = "",collapse = "+")
10## [1] "a1+a2+a3+a4+a5"
这样总结一下,sep连接的是元素间的扩展,collapse是一种元素间的折叠坍缩
与paste0函数的区别
paste0函数,默认sep=""是两个函数唯一的区别
1paste(c("a", "b","c"),1:3)##默认空格符
2## [1] "a 1" "b 2" "c 3"
3paste(c("a", "b","c"),1:3,sep=" ")
4## [1] "a 1" "b 2" "c 3"
5paste(c("a", "b","c"),1:3,sep="")
6## [1] "a1" "b2" "c3"
7#如果两个向量长度不同
8paste(c("a", "b","c"),1:5)##超出范围后继续从前向后连接
9## [1] "a 1" "b 2" "c 3" "a 4" "b 5"
10#paste0的表现
11paste0(c("a", "b","c"),1:3)#默认元素连接为sep=""
12## [1] "a1" "b2" "c3"
END