I am looking for a pair of R commands that dump a dataframe to the disk and that are able to recreate the same dataframe from the dump.
I suppose write.table is the de facto for export/import but it fails in the following example since it doesn’t preserve the type of the columns:
df = data.frame('foo' = 'bar')
df$foo = as.character(df$foo)
typeof(df$foo)
# = "character"
write.table(df,'~/df.rdata')
df2 = read.table('~/df.rdata')
typeof(df2$foo)
# = "integer"
As @TylerRinker said,
dputandsaveare probably the most fitting.…but
saveandloadare sometimes a bit inconvenient in that you givesavethe names of the objects to save, and thenloadloads the objects back into those names.An alternative is
saveRDSandreadRDS(yes, the naming is a bit weird!). They are a bit more low-level and saves a single object:Also note the use of
stringsAsFactors=FALSEwhen creating the data frame…