【问题标题】:Function overwrites the same object every time: how can I avoid this?函数每次都会覆盖同一个对象:我怎样才能避免这种情况?
【发布时间】:2020-01-18 02:18:57
【问题描述】:

我想为我所做的每个回归创建一个对象(其中 17 个)。理想情况下,该函数应该创建 17 个不同的对象,我以后可以使用它们。目前它只是在前一个之上写一个对象。我怎样才能避免这种情况?如果对象部分地以特定的“文件名”命名,那么最好能够在之后区分它们。

  dat <- read.csv(file = filename)
  reg2<<- lm(dat[,17]~dat[,6]+dat[,7])
  }

for (f in filenames) {
    upload(f)
}

【问题讨论】:

    标签: r


    【解决方案1】:

    这是函数内部全局赋值&lt;&lt;- 的最大问题之一。将您的函数return() 设置为模型,而不是分配,然后在函数外部进行分配。

    # function returns the result, doesn't assign it
    upload <- function(filename) {
      dat <- read.csv(file = filename)
      lm(dat[,17]~dat[,6]+dat[,7])
    }
    
    # assignment happens outside the function (like almost every other R function)
    # this way you can use whatever name you want
    reg2 <- upload("hello.csv")
    reg3 <- upload("world.csv")
    
    # or use a for loop
    reg <- list()
    for (f in filenames) {
      reg[[f]] <- upload(f)
    }
    
    # or use lapply for the same effect more concisely
    reg <- lapply(filenames, upload)
    names(reg) = filenames)
    
    # You can now access individual list elements with [[
    summary(reg[["hello.csv"]])
    
    # Or extract all the model summary stats into a nice data frame
    dplyr::bind_rows(lapply(reg, broom::glance))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 2018-03-25
      • 1970-01-01
      • 2011-12-28
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多