Tuesday 23 June 2015

R : write.table : Writing data to file

“write.table” function is used to write data to a file (or) connection.
Syntax
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 = "")

Parameter
Description
x
Represents the data to be written to a file. Usually x can be a data frame (or) a matrix.
file
File name to store the data. If the file name is “”, then data is written to console.
append
Id append is true, data is appended to file, else data is overridden.
quote
A logical value (TRUE or FALSE) or a numeric vector. If TRUE, any character or factor columns will be surrounded by double quotes. If a numeric vector, its elements are taken as the indices of columns to quote. In both cases, row and column names are quoted if they are written. If FALSE, nothing is quoted.
sep
Values in each row are separated by sep.
eol
The character(s) to print at the end of each line (row). For example, eol = "\r\n" will produce Windows' line endings on a Unix-alike OS, and eol = "\r" will produce files as expected by Excel:mac 2004.
na
Data to use for missing values.
dec
The string to use for decimal points in numeric or complex columns: must be a single character.
row.names
It is a logical value indicating whether the row names of x are to be written along with x, or a character vector of row names to be written.
col.names
It is a logical value indicating whether the column names of x are to be written along with x, or a character vector of column names to be written. See the section on ‘CSV files’ for the meaning of col.names = NA.
qmethod
A character string specifying how to deal with embedded double quote characters when quoting strings.
fileEncoding
Specifies the encoding to use while saving to file.

Following snippet write employee details to the file “employee.txt”.

> table1 = data.frame(firstName=c("Hari Krishna","Joel","Rama Krishna","Sudheer"), lastName=c("Gurram", "Chelli", "Gurram", "Ganji"))
> 
> table1
     firstName lastName
1 Hari Krishna   Gurram
2         Joel   Chelli
3 Rama Krishna   Gurram
4      Sudheer    Ganji
> 
> write.table(table1, "employee.txt", row.names=FALSE)

“employee.txt” file is located in your working directory (use getwd() to know your working directory).

employee.txt contains following data.

"firstName" "lastName"
"Hari Krishna" "Gurram"
"Joel" "Chelli"
"Rama Krishna" "Gurram"

"Sudheer" "Ganji"



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment