如何存储要在函数

时间:2016-11-02 12:12:00

标签: r function

我有一个函数,它逐行读入一个非常大的文本文件。 在使用我的函数之前,我创建了一个填充NA的列表。

当满足特定条件时,该函数将+1添加到列表中的特定位置。但这只是在函数内部工作。如果我在应用后打印我的列表,则会再次显示初始列表(填写NA' s。)

如何以可以在函数外部使用它们的方式存储值?

lion<-lapply(1, function(x) matrix(NA, nrow=2500, ncol=5000))

processFile = function(filepath) {
  con = file(filepath, "rb")

  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    y <- line
    y2 <- strsplit(y, "\t")
    x <- as.numeric(unlist(y2))
    if( x[2] <= 5000 & x[3] <= 2500) {

    lion[[1]][trunc(x[3] + 1), trunc(x[2])] <- lion[[1]][trunc(x[3] + 1), trunc(x[2])]
  }
  }

  close(con)

}

1 个答案:

答案 0 :(得分:0)

您必须将列表作为函数的最后一部分返回:

processFile = function(filepath) {
  con = file(filepath, "rb")

  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    y <- line
    y2 <- strsplit(y, "\t")
    x <- as.numeric(unlist(y2))
    if( x[2] <= 5000 & x[3] <= 2500) {

    lion[[1]][trunc(x[3] + 1), trunc(x[2])] <- lion[[1]][trunc(x[3] + 1), trunc(x[2])]
  }
  }

  close(con)
  return(lion)
}

这样,您可以使用lion <- processFile(yourfile)

调用您的函数

或者,您可以在执行函数时将列表分配给.GlobalEnv:

processFile = function(filepath) {
  con = file(filepath, "rb")

  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    y <- line
    y2 <- strsplit(y, "\t")
    x <- as.numeric(unlist(y2))
    if( x[2] <= 5000 & x[3] <= 2500) {

    lion[[1]][trunc(x[3] + 1), trunc(x[2])] <- lion[[1]][trunc(x[3] + 1), trunc(x[2])]
  }
  }

  close(con)
  assign("lion", lion, envir = .GlobalEnv)
}