164

I made a data.frame in R that is not very big, but it takes quite some time to build. I would to save it as a file, which I can than again open in R?

Borut Flis
  • 15,715
  • 30
  • 92
  • 119

3 Answers3

213

There are several ways. One way is to use save() to save the exact object. e.g. for data frame foo:

save(foo,file="data.Rda")

Then load it with:

load("data.Rda")

You could also use write.table() or something like that to save the table in plain text, or dput() to obtain R code to reproduce the table.

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • 2
    There is also `dump` and files created would be `source()`-ed, although the `help(dump)` page says `save` is "safer". – IRTFM Dec 01 '11 at 17:44
  • 4
    I always prefer storing data in plain text, so I'd prefer `dump()` over `save()`, and `write.table()` over `dump()` – Sacha Epskamp Dec 01 '11 at 17:56
  • Am I correct that write.table won't preserve things like having set up a column of 0's and 1's as a factor, but that `save()` / `load()` will? If so, that's something to take into account as well. I typically have a section of processing some .csv files and once I get them where I like them, I prefer to save them so I don't have to re-run that code every time I re-visit my project. So, preserving that work/tweaks to the structure is important to consider. – Hendy Jul 19 '13 at 18:46
  • 4
    Yes. `dump()` also saves the structure. The nice thing about `write.table` is that it writes tables in a way many software can import. – Sacha Epskamp Jul 19 '13 at 20:52
  • 2
    This saves rather more than just the dataframe. See ``saveRDS`` to save a dataframe without its name (dhendrickson has an answer on that). – PatrickT Dec 18 '15 at 06:05
112

If you are only saving a single object (your data frame), you could also use saveRDS.
To save:

saveRDS(foo, file="data.Rda")

Then read it with:

bar <- readRDS(file="data.Rda")

The difference between saveRDS and save is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.

ahoffer
  • 6,347
  • 4
  • 39
  • 68
dhendrickson
  • 1,247
  • 1
  • 9
  • 8
4

If you have a data frame named df, you can simply export it to same directory with:

write.csv(df, "output.csv", row.names=FALSE, quote=FALSE) 

credit to: Peter and Ilja, UMCG, the Netherlands.

PatrickT
  • 10,037
  • 9
  • 76
  • 111