Appendix C. Exporting data from R

 

In chapter 2, we reviewed a wide range of methods for importing data into R. But there are times that you’ll want to go the other way—exporting data from R—so that data can be archived or imported into external applications. In this appendix, you’ll learn how to output an R object to a delimited text file, an Excel spreadsheet, or a statistical application (such as SPSS, SAS, or Stata).

C.1. Delimited text file

You can use the write.table() function to output an R object to a delimited text file. The format is

write.table(x, outfile, sep=delimiter, quote=TRUE, na="NA")

where x is the object and outfile is the target file. For example, the statement

write.table(mydata, "mydata.txt", sep=",")

would save the dataset mydata to a comma-delimited file named mydata.txt in the current working directory. Include a path (for example, "c:/myprojects/mydata. txt") to save the output file elsewhere. Replacing sep="," with sep="\t" would save the data in a tab-delimited file. By default, strings are enclosed in quotes ("") and missing values are written as NA.

C.2. Excel spreadsheet

The write.xlsx() function in the xlsx package can be used to save an R data frame to an Excel 2007 workbook. The format is

library(xlsx)
write.xlsx(x, outfile, col.Names=TRUE, row.names=TRUE,
             sheetName="Sheet 1", append=FALSE)

For example, the statements

library(xlsx)
write.xlsx(mydata, "mydata.xlsx")

C.3. Statistical applications