可以这样做,但您需要提供一个在append 模式下打开的连接。
data <- list(1:10, c(1,2,3))
fcon <- file('sample.R', 'a')
lapply(data, dput, file = fcon)
close(fcon)
> readLines('sample.R')
[1] "1:10" "c(1, 2, 3)"
如果您查看dput 来源,原因就很清楚了:
> dput
function (x, file = "", control = c("keepNA", "keepInteger",
"showAttributes"))
{
if (is.character(file))
if (nzchar(file)) {
file <- file(file, "wt")
on.exit(close(file))
}
else file <- stdout()
...
}
我们可以看到,如果file参数是字符,文件连接将以write模式打开,现有内容将被覆盖。
无论如何,按照评论中的建议,使用dump 会更简单,因为dump 有一个append 参数,它决定了连接将以何种模式打开。
> dump
function (list, file = "dumpdata.R", append = FALSE, control = "all",
envir = parent.frame(), evaluate = TRUE)
{
if (is.character(file)) {
...
if (nzchar(file)) {
file <- file(file, ifelse(append, "a", "w"))
on.exit(close(file), add = TRUE)
}
else file <- stdout()
}
...
}