分享

R语言的输出函数cat,sink,writeLines,write.table

 gearss 2018-04-25

根据输出的方向分为输出到屏幕和输出到文件。

1.cat函数即能输出到屏幕,也能输出到文件.

使用方式:cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,append = FALSE)

有file时,输出到file。无file时,输出到屏幕。

append参数:布尔值。TRUE时,输出内容追加到文件尾部。FALSE,覆盖文件原始内容。

1
2
3
cat("hello")
hello
cat("hello",file="D:/test.txt",append=T)

  

2.sink函数将输出结果重定向到文件。

使用方式:sink(file = NULL, append = FALSE, type = c("output", "message"),split = FALSE)

append参数:布尔值。TRUE时,输出内容追加到文件尾部。FALSE,覆盖文件原始内容。

1
2
3
sink("hello.txt") # 将输出重定向到hello.txt
cat("hello")
sink() # 结束重定向

 

3.writeLines函数将字符串向量输出到文件中(会覆盖原始内容)

使用方式:writeLines(text, con = stdout(), sep = "\n", useBytes = FALSE)

text:字符串向量;con:输出文件

 a=c("one","tew")
 writeLines(a,con="D:/test.txt",sep="\t")

问题:每调用一次就会覆盖原始内容?

 

4.write.table()函数将dataframe的内容输出到文件。

使用方式:write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = c("escape", "double"),fileEncoding = "")

1
2
3
m=matrix(1:12,nrow=3)
df=as.data.frame(m)
write.table(df,file="D:/test.txt",append=T,row.names=F)

  

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多