Fabi Fabi - 1 month ago 5
R Question

How to store values to use outside of function

I have a function which reads in a very large text file line by line.
I create a list filled with NA's before I use my function.

The function adds +1 to a specific position within the list when a certain condition is fulfilled. But this somehow works only inside the function. If I print my list after I applied it, again the initial list is shown (filled with NA's).

How can I store the values in such a way that I can use them outside the function?

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)

}

Answer

You either have to return the list as the last part of your function:

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)
}

This way, you can call your function with lion <- processFile(yourfile)

Alternatively, you can assign the list to the .GlobalEnv while executing the function:

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)
}