R:寫檔案(輸入與輸出)
Write.table()函式的用法read.table()非常相似,只不過它把資料框寫入檔案而不是從檔案中讀取。引數和選項:
write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",eol = "\n", na = "NA", dec = ".", row.names = TRUE,col.names = TRUE, qmethod = c("escape", "double"))
> kids <- c( "Jack", "Jill", "Kate" )
> ages <- c( 25, 36, 18 )
> d <- data.frame( kids, ages, stringsAsFactors=FALSE )
> write.table( d, "D:/RCodes/dfile.txt" )
如果想把矩陣寫入檔案,只需要宣告不要列名和行名即可。
> x <- matrix( scan("D:/RCodes/readM.txt", quiet=TRUE),nrow=5, byrow=TRUE )
> write.table( x, "D:/RCodes/writeM.txt", row.names=FALSE, col.names=FALSE )
cat()函式同樣可以用來寫入檔案,一次寫入一部分。
cat( "abc\n", file="D:/RCodes/writeCAT.txt" )
cat( "def\n", file="D:/RCodes/writeCAT.txt",append=TRUE )
cat( file="writeCAT.txt", 1, 2, "xyz\n" )
第一次呼叫cat()時在指定目錄下建立了檔案writeCAT.txt,包含一行內容”abc”。第二次呼叫追加了第二行,這個檔案會在每一次操作之後自動儲存。cat()函式可以寫多個欄位,上面最後一行的程式碼會生成只有一行內容的檔案writeCAT.txt。
還可以使用writeLines()函式,它是readLines()的相對。如果用的是連線,則必須設定引數“w”來指明是要寫檔案而非讀取。
c <- file( "file", "w" )
writeLines( c( "abc", "de", "f" ), c )
close( c ) #這裡需要主動關閉檔案