R中paste cat和sink的用法

1 paste的用法

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

通过具体例子来看sepcollapse参数

> 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"

再看一个官方例子

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

制表符分割

> paste('Sample',letters[1:5],sep = '-',collapse = '\t')
[1] "Sample-a\tSample-b\tSample-c\tSample-d\tSample-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用法:输出结果(直接输出或写入文件)

cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,
    append = FALSE)

举例

> cat('The content of hello.txt')
The content of hello.txt
> cat('The content of hello.txt',file = 'hello.txt')

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

file.show('hello.txt')

截图如下


R中paste cat和sink的用法_第1张图片

cat也有sep参数

> 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

注意以下两个命令的区别

cat(paste(c('Sample',LETTERS[1]), collapse = '\t'))
cat(paste(c('Sample',LETTERS[1]), collapse = '\n'))

结果分别是

> cat(paste(c('Sample',LETTERS[1]), collapse = '\t'))
Sample  A
> cat(paste(c('Sample',LETTERS[1]), collapse = '\n'))
Sample
A

3 sink的用法

sink(file = NULL, append = FALSE, type = c("output", "message"),
     split = FALSE)

举例

> sink('sink.txt')
> cat('The first line of sink.file\n')
> cat('The second line of sink file \n')
> sink()
> file.show('sink.txt')
R中paste cat和sink的用法_第2张图片
sink

你可能感兴趣的:(R中paste cat和sink的用法)