Short Question

After formatting a dataframe in R with class information like "Date", "Factor", and etc. how to save the dataframe while preserving the class information. Consequently how to load the information back to a new R Project with preserving the above class information.

Long Question

I have created following dataframe with class information,

names <- c("Adrew", "Vikie", "Penny", "Samantha") 
date <- as.Date(c("1984-12-28", "1986-10-18", "1986-11-30", "1987-11-30"))
gender <- c("M", "M", "S", "S")

df <- data.frame(names, date, gender)

df$gender <- factor(df$gender,
                   levels = c("M", "S"), 
                   labels = c(1,2), 
                   order = FALSE)


and the classes are factor, date, factor

method 01

then write the dataframe in csv format and read it

write.csv(df, "df.csv")
dfcsv <- read.csv("df.csv")


and the daraframe classes are changed

method 02

then tried to write the file using table export method

write.table(df, "df.R")
dftable <- read.table("df.R")


again the data frame classes had been changed


is there a proper method to write or save a data frame with preserving the class information like date, factor, etc information intact, and conversely how to load it back.


2 Answers 2


The best way to achieve this would be to save the data as an R data file using either save() or saveRDS():

# option 1
save(df, file="data.Rdata")

# option 2
saveRDS(df, file="data2.Rds")
df <- readRDS("data2.Rds")
  • $\begingroup$ This works perfectly, thank you. $\endgroup$ May 3, 2021 at 17:36


It is possible to write ASCII text representation of an R object with the use of dput, dump, dget and source. And with this it is possible to preserve the class information


saving the file

to save the file use the dget and/or dump function, and to make sure that the file preserve the class information use the argument control = "all"

the dump function take a list of dataframes as input which can be listed as c("df", "df1", "df3") and in the other hand dput will only output a single dataframe to a file.


dput(df, file = "dput.R", control = "all")


dump(c("df", "df2", "df3"), file = "dump.R", control = "all")


reading the file

to read the file use the dget function for dput files and source function for dump as mentioned,

dput -> dget

df3 <- dget(file =  "dput.R")

dump -> source




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.