R Write Data to File


write(...) function writes data to a file. It's usage is:

write(x, file = "data",
ncolumns = if(is.character(x)) 1 else 5,
append = FALSE, sep = " ")


x: The data to be written, including vector, matrix, scalar, but not data frame
file: Out file name, if empty, then print to the screen
ncolumns: Number of columns in the file
append: Append model, otherwise new file will be created
sep: Seperator, default is " "


Let's see a matrix example (we will print to the screen, you may give a file name for writing to the file):

>x <- matrix(c(3,5,7,1,9,4),nrow=3,ncol=2,byrow=TRUE)
>write(x,"")

3 7 9 5 1
4

>write(x,"",ncolumns=2,sep=",")

3,7
9,5
1,4


write.table(...) write data frame to a file.

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


Let's write the data set BOD to the screen:

>write.table(BOD,"",sep=",")

"Time","demand"
"1",1,8.3
"2",2,10.3
"3",3,19
"4",4,16
"5",5,15.6
"6",7,19.8


write.csv has similar function with write.table.