[英]using the dput function with lapply
是否可以在循環中使用dput而不在每次迭代中覆蓋文件,即
f<-function(x){
dput(x,file="sample.R")
}
lapply(data,function(y) {f(y)})
可以這樣做,但是您需要提供一個在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
參數為character,則文件連接將以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()
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.