R語言的輸出

R語言的輸出函數有cat、sink、writeLines、write.table

1)cat

cat函數即能輸出到屏幕,也能輸出到文件

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

eg:
>cat("要添加的內容") ##結果:要添加的內容
>cat("a",file="d:/面試.txt",append=TRUE) ##再次打開面試.txt最後多了a

 

2)sink

sink函數將輸出結果定向到文件

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

eg:
> sink("d:/面試.txt") ##以下的內容定向輸入到面試
> cat("shemegui")     ##清除面試原內容,添加
> cat("jssjjs")       ##繼續添加
> sink("d:/面試.txt") ##重定向
> cat("qqqqqq")       ##再次清除添加
 

3)writeLines

writeLines函數將字符串向量輸出到文件中(會覆蓋原始內容)

writeLines(text, con = stdout(), sep = "\n", useBytes = FALSE)

eg:
> a<-c("haha","hehe")
> writeLines(a,con="d:/面試.txt",sep="\t")  ##結果:haha	hehe	

> a=c("hahaha","hehehe") ##可以=號
> writeLines(a,con="d:/面試.txt",sep="\n") ##換行

4)write.table

write.table函數將dataframe的內容輸出到文件

參數說明

x 寫入的對象的名稱
file  文件名(缺省時對象直接被“寫”在屏幕上)
append 是否爲增量寫入
quote 一個邏輯型或者數值型向量:如果爲TRUE,則字符型變量和因子寫在雙引 號""中;若quote是數值型向量則代表將欲寫在""中的那些列的列標。(兩種 情況下變量名都會被寫在""中;若quote = FALSE則變量名不包含在雙引號中)
sep 文件中的字段分隔符
eol  指定行尾符,默認爲'\n'
na 表示缺失數據的字符
dec 用來表示小數點的字符
row.names 一個邏輯值,決定行名是否寫入文件;或指定要作爲行名寫入文件的字符型 向量
col.names 一個邏輯值(決定列名是否寫入文件);或指定一個要作爲列名寫入文件中 的字符型向量
qmethod 若quote=TRUE,則此參數用來指定字符型變量中的雙引號"如何處理: 若參數值爲"escape" (或者"e",缺省)每個"都用\"替換;若值爲"d"則每 個"用""替換
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 = "")

eg:
> m<-matrix(1:12,nrow=3)
> dd=as.data.frame(m)
> write.table(dd,file="d:/面試.txt",append=TRUE,row.names=FALSE)
##結果(加了列名)
hahaha
hehehe
"V1" "V2" "V3" "V4"
1 4 7 10
2 5 8 11
3 6 9 12

> write.table(dd,file="d:/面試.txt",append=TRUE,col.names=FALSE)
##再加一句,結果
hahaha
hehehe
"V1" "V2" "V3" "V4"
1 4 7 10
2 5 8 11
3 6 9 12
"1" 1 4 7 10
"2" 2 5 8 11
"3" 3 6 9 12

> write.table(dd,file="d:/面試.txt",append=F)
##繼續測試
"V1" "V2" "V3" "V4"
"1" 1 4 7 10
"2" 2 5 8 11
"3" 3 6 9 12

輸出爲表格:

> write.csv(dd,file="d:/tab.csv")   

> write.table(dd,file="d:/sb.csv")

>write.csv(dd,file="d:/sb.xls")

>write.table(dd,file="d:/sb.xlsx")  ##結果一致

以下純粹鬧着玩的

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章