考虑一下:
我有fav.activities
带有对象名称的向量:
fav.activities <- c("swiming", "basketball", "baseball", "football")
names(fav.activities) <- c("Tom", "Ben", "Paul", "Ann")
我现在想保存整个文件。用过的
write(fav.activities)
但不保存对象的名称。我该怎么做?
考虑一下:
我有fav.activities
带有对象名称的向量:
fav.activities <- c("swiming", "basketball", "baseball", "football")
names(fav.activities) <- c("Tom", "Ben", "Paul", "Ann")
我现在想保存整个文件。用过的
write(fav.activities)
但不保存对象的名称。我该怎么做?
write()
使用and将输出发送到屏幕/文件时cat()
删除该属性:"names"
R> cat(fav.activities)
swiming basketball baseball footballR>
如果您希望将向量读出到文本/分隔文件,一种选择是强制转换为矩阵并使用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\""
额外\"
的就是 R 如何将字符串打印到控制台。在我的操作系统中,文件如下所示:
$ cat foo.txt
"Tom" "Ben" "Paul" "Ann"
"swiming" "basketball" "baseball" "football"
即它是一个空格分隔的文件。可以定义其他分隔符;见?write.table
。
如果您只想读取向量以在以后的 R 会话中使用,那么save()
或者saveRDS()
是两个选项:
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)
有了这个输出:
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
save()
和之间的主要区别在于saveRDS()
前者保存对象及其名称,因此只能使用相同的对象名称恢复。而saveRDS()
只是序列化对象,然后必须在将序列化对象加载到 R 会话时将其分配给对象。
如果要以文本格式保存数据,请使用:
write.table(fav.activities, file = "filename.txt", col.names = FALSE)
从文本文件恢复对象:
dat <- read.table("filename.txt", stringsAsFactors = FALSE)
fav.activities <- structure(dat[ , 2], .Names = dat[ , 1])
如果要保存 R 对象的表示,请使用:
save(fav.activities, file = "filename.RData")
要恢复对象:
load("filename.RData")