R语言初学者之-paste函数以及格式化输出
Concatenate Strings #连接字符串
Description
Concatenate vectors after converting to character.
将待连接项中的内容转化成字符串,将每项中的字符串,按照顺序连接起来。
Usage
paste (…, sep = " ", collapse = NULL)
paste0(…, collapse = NULL)
Arguments
…
一个或多个将被转化成字符串并连接起来的项。
sep
不同项元素(项多于2才有意义)连接起来的字符串之间的分隔符,用于区别不同项元素之间的分隔符。
collapse
一个可选的分隔符,用于结果之间的分割。
p1<-paste(c(1,'1','a','b'))
print (p1)
p2<-paste(c(1,'1','a','b'),sep=',')
print (p2)
p3<-paste(c(1,'1','a','b'),colaspe=',')
print (p3)
p4<-paste(c(1,'1','a','b'),c(1:5),sep=',',colaspe='.')
print (p4)
[1] “1” “1” “a” “b”
[1] “1” “1” “a” “b”
[1] “1 ,” “1 ,” “a ,” “b ,”
[1] “1,1,.” “1,2,.” “a,3,.” “b,4,.” “1,5,.”
paste0(…, collapse) is equivalent to paste(…, sep = “”, collapse), slightly more efficiently.
字符串格式化输出
p1<-paste(c(1,'1','a','b'))
sprintf ('p1=%s',p1)
p2<-paste(c(1,'1','a','b'),sep=',')
sprintf ('p2=%s',p2)
p3<-paste(c(1,'1','a','b'),colaspe=',')
sprintf ('p3=%s',p3)
p4<-paste(c(1,'1','a','b'),c(1:5),sep=',',colaspe='.')
sprintf ('p4=%s',p4)
p5<-paste(c(1,'1','a','b'),c(1:5),sep='',colaspe='.')
sprintf ('p5=%s',p5)
p6<-paste0(c(1,'1','a','b'),c(1:5),colaspe='.')
sprintf ('p6=%s',p6)
输出结果
[1] "p1=1" "p1=1" "p1=a" "p1=b"
[1] "p2=1" "p2=1" "p2=a" "p2=b"
[1] "p3=1 ," "p3=1 ," "p3=a ," "p3=b ,"
[1] "p4=1,1,." "p4=1,2,." "p4=a,3,." "p4=b,4,." "p4=1,5,."
[1] "p5=11." "p5=12." "p5=a3." "p5=b4." "p5=15."
[1] "p6=11." "p6=12." "p6=a3." "p6=b4." "p6=15."