在 R 中读取和写入数据/文件的方法有很多种。为了阅读,您可能需要查看:read.table
, read.csv
, readLines
, source
, dget
, load
, unserialize
, and readRDS
。对于写作,你会想要看看write.table
, writeLines
, dump
, dput
, save
, serialize
, and saveRDS
.
x <- 1:3
# [1] 1 2 3
save(x, file = "myvector.rda")
# Change x to prove a point.
x <- 4:6
x
# [1] 4 5 6
# Better yet, we could remove it entirely
rm(x)
x
# Error: object 'x' not found
# Now load what we saved to get us back to where we started.
load("myvector.rda")
x
# [1] 1 2 3
或者,您可以使用saveRDS
and readRDS
-- 最佳实践/惯例是使用.rds
扩大;但请注意,加载对象是slightly不同的是saveRDS
不保存对象名称:
saveRDS(x, file = "myvector_serialized.rds")
x <- readRDS("myvector_serialized.rds")
最后,saveRDS
是一个较低级别的函数,因此一次只能保存一个对象。传统的save
方法允许您同时保存多个对象,但如果您在不同的项目/文件/脚本中重复使用相同的名称,可能会成为一场噩梦......