【问题标题】:using the dput function with lapply将 dput 函数与 lapply 一起使用
【发布时间】:2015-07-01 15:59:58
【问题描述】:

是否可以在循环中使用 dput 而不会在每次迭代中覆盖文件,即,

f<-function(x){

dput(x,file="sample.R")

}


lapply(data,function(y) {f(y)})

【问题讨论】:

  • 也许你想看看dumpappend 参数?
  • 就风格而言,最好以函数式的方式使用 R 中的函数式构造,即没有副作用。对于for 构造,这将是一个很好的用例。
  • 您可以使用全局变量,或将变量传递给您的函数i 作为计数器。 paste0("sample", i, ".R")

标签: r loops lapply


【解决方案1】:

可以这样做,但您需要提供一个在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()
    }
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2012-11-16
    • 1970-01-01
    • 2011-10-23
    相关资源
    最近更新 更多