Reputation: 28339
Consider this:
I have vector fav.activities
with names of the objects:
fav.activities <- c("swiming", "basketball", "baseball", "football")
names(fav.activities) <- c("Tom", "Ben", "Paul", "Ann")
I want to save the whole file now. Used
write(fav.activities)
But names of the objects aren't saved. How should I do this?
Upvotes: 0
Views: 1626
Reputation: 81693
If you want to save your data in text format, use:
write.table(fav.activities, file = "filename.txt", col.names = FALSE)
To restore the object from the text file:
dat <- read.table("filename.txt", stringsAsFactors = FALSE)
fav.activities <- structure(dat[ , 2], .Names = dat[ , 1])
If you want to save a representation of the R object, use:
save(fav.activities, file = "filename.RData")
To restore the object:
load("filename.RData")
Upvotes: 2
Reputation: 174823
write()
uses cat()
and that drops the "names"
attribute when sending the output to the screen/file:
R> cat(fav.activities)
swiming basketball baseball footballR>
If you want the vector read out to a text/delimited file, one option is to coerce to a matrix and use write.table()
:
R> write.table(t(as.matrix(fav.activities)), "foo.txt", row.names = FALSE)
R> readLines("foo.txt")
[1] "\"Tom\" \"Ben\" \"Paul\" \"Ann\""
[2] "\"swiming\" \"basketball\" \"baseball\" \"football\""
The extra \"
are just how R prints the strings to the console. From my OS the file looks like this:
$ cat foo.txt
"Tom" "Ben" "Paul" "Ann"
"swiming" "basketball" "baseball" "football"
I.e. it is a space separated file. Other separators can be defined; see ?write.table
.
If you just want to read the vector out for use in a later R session, then save()
or saveRDS()
are two options:
ls()
save(fav.activities, file = "obj.rda")
rm(list = ls())
load("obj.rda")
ls()
saveRDS(fav.activities, file = "obj2.rds")
new.fav <- readRDS("obj2.rds")
ls()
all.equal(fav.activities, new.fav)
With this output:
R> ls()
[1] "fav.activities"
R> save(fav.activities, file = "obj.rda")
R> rm(list = ls())
R> load("obj.rda")
R> ls()
[1] "fav.activities"
R> saveRDS(fav.activities, file = "obj2.rds")
R> new.fav <- readRDS("obj2.rds")
R> ls()
[1] "fav.activities" "new.fav"
R> all.equal(fav.activities, new.fav)
[1] TRUE
The main difference between save()
and saveRDS()
is that the former save the object and it's name so can only ever be restored with the same object name. Whereas saveRDS()
just serialises the object which then has to be assigned to an object upon loading the serialised object into an R session.
Upvotes: 3