Exporting Data from R to Text Files

April 27th, 2009

Exporting small or medium sized data sets from the R environment to text files is a straightforward task. The two functions that are most useful for this operation are write.csv and write.table which export data to comma separate variable format or a text format with a different character used to indicate separate columns of data.

If we had a data frame in R, for example with a name sales.data, then the basic function call to export this data to a csv file would be:

write.csv(sales.data, "SalesData.csv")

Data in R can have separate row names and the default option for write.csv is to include row names. If there are no row names then we end up with a redundant column of sequential numbers. As an example we might have:

"","Month","Year","Units Sold"
"1","Jan","2009",12500
"2","Feb","2009",11750
...

The function can be instructed to ignore the row names by supplying an additional argument, so the function call would’ve been:

write.csv(sales.data, "SalesData.csv", row.names = FALSE)

The text file would now read:

"Month","Year","Units Sold"
"Jan","2009",12500
"Feb","2009",11750
...

The comma separated variable format is not the only text file format that can be created using R and the function write.table can be used if a variation is required. The function call is very similar to the one used above and if we wanted to export the anscombe data set that is available within R then this code could be used:

write.table(anscombe, "Data\\anscombe.txt", row.names = FALSE)

This would create a text file like this:

"x1" "x2" "x3" "x4" "y1" "y2" "y3" "y4"
10 10 10 8 8.04 9.14 7.46 6.58
8 8 8 8 6.95 8.14 6.77 5.76
...

so we can see that the default option is to use a space to separate the columns of data in the output file. The character used to separate the columns can be specified with the sep argument to this function. An example would be:

write.table(Orange, "Data\\orange.txt", sep = "\t", row.names = FALSE)

to give the following output:

"Tree"	"age"	"circumference"
"1"	118	30
"1"	484	58
...

Other options for these functions are detailed in the respective help pages.

Comments are closed.