考虑一下:
我有向量fav.activities
,其中包含对象的名称:
fav.activities <- c("swiming", "basketball", "baseball", "football")
names(fav.activities) <- c("Tom", "Ben", "Paul", "Ann")
我想立即保存整个文件。使用
write(fav.activities)
但是不保存对象的名称。我该怎么做?
答案 0 :(得分:3)
write()
使用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会话时必须将该对象分配给对象。
答案 1 :(得分:2)
如果要以文本格式保存数据,请使用:
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")