T.B90 T.B90 - 5 days ago 5
R Question

Can an imported dataframe be converted to a function?

I have a simple question, but up to now I could not find a generic solution for this:
Let's say I have a dataframe

>df
that I got from a .csv file

> df <- read.csv("foo.csv")
> df
a b
1 1 D
2 2 E
3 3 F


I want to save this dataframe in a .R file to source it later again, but without reading the .csv file. It should be inside the source file, so the file can be shared with other users.
Is there a possibility to convert this dataframe in a written function, like
df<-data.frame(a=c(1,2,3),b=c("D","E","F"))


Answer

We can use save or save.image at the end of the session as a .RData

save.image("yourfile.RData")

and then load it when necessary so that all the objects created earlier will be loaded

load("yourfile.RData")

If we need to save only individual objects, just name the objects and file

save(df, file = "yourfile.RData")
load("yourfile.RData")
Comments