Category Archives: Working with data files

Exporting a dataset from R

R allows you to export datasets from the R workspace to the CSV and tab-delimited file formats.

To export a dataset named dataset to a CSV file, use the write.csv function.

> write.csv(dataset, "filename.csv")

For example, to export the Puromycin dataset (included with R) to a file names puromycin_data.csv, use the command:

> write.csv(Puromycin, "puromycin_data.csv")

This command creates the file and saves it to your working directory, which by default is your ‘My Documents’ folder (for Windows users) or your home folder (for Mac and Linux users). To save the file somewhere other than in the working directory, enter the full path for the file as shown.

> write.csv(dataset, "C:/folder/filename.csv")

If a file with your chosen name already exists in the specified location, R overwrites the original file without giving a warning. You should check the files in the destination folder beforehand to make sure you are not overwriting anything important.

The write.table function allows you to export data to a wider range of file formats, including tab-delimited files. Use the sep argument to specify which character should be used to separate the values. To export a dataset to a tab-delimited file, set the sep argument to "\t" (which denotes the tab symbol), as shown below.

> write.table(dataset, "filename.txt, sep="\t")

By default, the write.csv and write.table functions create an extra column in the file containing the observation numbers. To prevent this, set the row.names argument to F.

> write.csv(dataset, "filename.csv, row.names=F)

With the read.table function, you can also prevent variable names from being placed in the first line of the file with the col.names argument.

> write.table(dataset, "filename.txt, sep="\t", col.names=F)

Social Widgets powered by AB-WebLog.com.