R中paste cat和sink的用法

2019-12-26 17:54:43 浏览数 (3)

1 paste的用法

代码语言:javascript复制
paste(..., sep=" ", collapse=NULL)

  • 本质是把输入的term转变为string,和as.character意思一样。然后进行连接。
  • 每个term之间以sep参数分隔开
  • collapse是把结果进行处理,也可以认为怎么来对结果进行折叠。

通过具体例子来看sepcollapse参数

代码语言:javascript复制
> paste('Sample',1:10,sep = '')
 [1] "Sample1"  "Sample2"  "Sample3"  "Sample4"  "Sample5"  "Sample6" 
 [7] "Sample7"  "Sample8"  "Sample9"  "Sample10"
> paste('Sample',1:10,sep = '_')
 [1] "Sample_1"  "Sample_2"  "Sample_3"  "Sample_4"  "Sample_5"  "Sample_6" 
 [7] "Sample_7"  "Sample_8"  "Sample_9"  "Sample_10"
> paste('Sample',LETTERS[1:5],sep = '-')
[1] "Sample-A" "Sample-B" "Sample-C" "Sample-D" "Sample-E"
> paste(rep('Sample',5),LETTERS[1:10],sep = '-')#自动对应补齐
 [1] "Sample-A" "Sample-B" "Sample-C" "Sample-D" "Sample-E" "Sample-F"
 [7] "Sample-G" "Sample-H" "Sample-I" "Sample-J"
> paste('Sample',letters[1:5],sep = '-', collapse = '~')
[1] "Sample-a~Sample-b~Sample-c~Sample-d~Sample-e"

再看一个官方例子

代码语言:javascript复制
> (nth <- paste0(1:12, c("st", "nd", "rd", rep("th", 9))))
 [1] "1st"  "2nd"  "3rd"  "4th"  "5th"  "6th"  "7th"  "8th"  "9th"  "10th" "11th" "12th"

制表符分割

代码语言:javascript复制
> paste('Sample',letters[1:5],sep = '-',collapse = 't')
[1] "Sample-atSample-btSample-ctSample-dtSample-e"
#为了更好的看清楚结果,cat一下
> cat(paste('Sample',letters[1:5],sep = '-',collapse = 't'))
Sample-a    Sample-b    Sample-c    Sample-d    Sample-e
#注意区分和上一条命令的区别,这里用`c连接
> cat(paste(c('Sample',letters[1:5]),sep = '-',collapse = 't'))
Sample  a   b   c   d   e
#换行
> cat(paste('Sample',letters[1:5],sep = '-',collapse = 'n'))
Sample-a
Sample-b
Sample-c
Sample-d
Sample-e

2 cat用法:输出结果(直接输出或写入文件)

代码语言:javascript复制
cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,
    append = FALSE)

举例

代码语言:javascript复制
> cat('The content of hello.txt')
The content of hello.txt
> cat('The content of hello.txt',file = 'hello.txt')

第二条命令不会显示任何信息,可以file.show查看

代码语言:javascript复制
file.show('hello.txt')

截图如下

cat也有sep参数

代码语言:javascript复制
> cat('Sample',1:10, sep = 'n')
Sample
1
2
3
4
5
6
7
8
9
10
> cat('Sample',1:10, sep = '-')
Sample-1-2-3-4-5-6-7-8-9-10

注意以下两个命令的区别

代码语言:javascript复制
cat(paste(c('Sample',LETTERS[1]), collapse = 't'))
cat(paste(c('Sample',LETTERS[1]), collapse = 'n'))

结果分别是

代码语言:javascript复制
> cat(paste(c('Sample',LETTERS[1]), collapse = 't'))
Sample  A
> cat(paste(c('Sample',LETTERS[1]), collapse = 'n'))
Sample
A

3 sink的用法

代码语言:javascript复制
sink(file = NULL, append = FALSE, type = c("output", "message"),
     split = FALSE)

举例

代码语言:javascript复制
> sink('sink.txt')
> cat('The first line of sink.filen')
> cat('The second line of sink file n')
> sink()
> file.show('sink.txt')

sink

1 人点赞