Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving a data file in R

Tags:

r

saving-data

I have successfully loaded a .txt file into R. I want to save the data so I can actually actively use it. What is the command for saving a file? Will I save the file to one of the existing packages (UsingR, MASS), or just as a separate file?

like image 985
Roswitha Blasche Avatar asked Apr 06 '11 08:04

Roswitha Blasche


People also ask

How do you save a data file in R?

To save data as an RData object, use the save function. To save data as a RDS object, use the saveRDS function. In each case, the first argument should be the name of the R object you wish to save. You should then include a file argument that has the file name or file path you want to save the data set to.


2 Answers

The command you look for is either one of these :

  • save() : saves the mentioned objects as R objects (extension .RData). These files are binary and can be read very quickly again with load()
  • write() : is a wrapper for cat() and is used to create text files from objects, usually matrices.
  • write.table() and write.csv() : are commands to write data frames as text files with a specific separator.

Check also sink(), used to redirect other output to a file (usually used for logging purposes).

Please read the manuals of R :

http://cran.r-project.org/doc/manuals/R-intro.pdf

http://cran.r-project.org/other-docs.html

Related questions :

  • Save a file interactively?
  • Saving a data frame as a binary file
  • How do you sink input and output to a text file in R?
like image 94
Joris Meys Avatar answered Oct 13 '22 03:10

Joris Meys


Why do you want to save the data out again - you don't need to save it to use it if you can load from .txt? If the loading from the txt file is not prohibitively costly in time (i.e. because it requires lots of processing and reformatting) I don't see the advantage of saving it in a different format. What if someone/you changes the .txt files?

Instead, and this is how I tend to work if the data aren't too big/complex, have a data import and processing script that contains the code to load the data, and process it if required, from the .txt file. This script is called from my analysis script so that the raw data are loaded, processed and available.

If the data import and processing/formatting is too costly to do each time you want to use the data, then saving out as an R object (via save()) as per @Joris Meys' answer.

like image 42
Gavin Simpson Avatar answered Oct 13 '22 02:10

Gavin Simpson