zoltanctoth
zoltanctoth

Reputation: 2927

Export dataframe in R and preserve types

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"

Upvotes: 2

Views: 1868

Answers (3)

Tommy
Tommy

Reputation: 40821

As @TylerRinker said, dput and save are probably the most fitting.

...but save and load are sometimes a bit inconvenient in that you give save the names of the objects to save, and then load loads the objects back into those names.

An alternative is saveRDS and readRDS (yes, the naming is a bit weird!). They are a bit more low-level and saves a single object:

df <- data.frame(foo = 'bar', stringsAsFactors=FALSE)
saveRDS(df, file='foo.rds')
df2 <- readRDS('foo.rds')
identical(df, df2)

Also note the use of stringsAsFactors=FALSE when creating the data frame...

Upvotes: 2

Andrie
Andrie

Reputation: 179448

Use the functions save and load.

save(df, file="filename.rdata")

And then load it again:

load("filename.rdata")

Upvotes: 2

Tyler Rinker
Tyler Rinker

Reputation: 109874

dput and save(objects, file="foo.RData") both preserve the column types. Rdata object with save is probably the smartest choice and can be reloaded with: load("foo.RData")

Upvotes: 2

Related Questions