Saving Data to Disk

I'm just beginning to learn more about this, so what follows may be less than optimal and certainly is not complete. At the time of writing, I am convinced that R is not the best data management tool available (actually, I don't know anybody who claims that it is). Not that R cannot do great things – it's just that its possibilities are so overwhelming. For instance, whereas other statistics software typically has exactly one (rectangular) data format (with perhaps older and newer versions), R will just use anything you like as data -- vectors, matrices, data.frames and probably many other objects (particularly those that belong to a defined class).

R files

R data files can be saved to disk in two ways.

Under normal circumstances, the best way is as follows:

write.table(mydata, file="name-of-file")

The object thus created will be of the class "data frame". Of course, "name-of-file" may be preceded by a path to the pertinent directory. It is recommmendable to add an extension to "name-of-file", i.e. to write "name-of-file.RData", for example. (But note that an object being called "xxx.RData" does not mean that it's a data frame – it may be anything!)

Another way is to "save" an object. This means that the object will retain the class it belongs to -- and its "object name".

save(myobject, file="name-of-file")

Note that upon reading data files it is necessary that you are aware of the command that has been used to save it. Otherwise, trouble may ensue.

Exporting to other statistics software

Just as in the case of reading data, saving data in a different format requires the libraryforeign to be loaded. Note, however, that this package is "frozen" (as of end of 2015); in other words, there won't be fixes or updates. A newer package, haven, can do similar things, but as yet is has not been thoroughly tested and so you may still encounter problems.

Stata

Assuming you have a data frame called mydata, you may save it as a Stata file with

write.dta(mydata,"name-of-Stata-file")

provided you have loaded package foreign. Some options are available which may be explained later. Beware of missing values, in whatever shape they may come.

If you encounter trouble (for instance, there may be an error message "empty string is not valid in Stata's documented format" which, even though it is nonsense – Stata has no problem with empty strings –, causes abortion of the procedure), you might install haven and try

write_dta(mydata,"name-of-Stata-file")

© W. Ludwig-Mayerhofer, R Guide | Last update: 28 Nov 2016