簡體   English   中英

將dput函數與lapply一起使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM