[R] returning dynamic variable names from function

Thomas Lumley tlumley at u.washington.edu
Thu Oct 16 20:17:38 CEST 2003


On Thu, 16 Oct 2003, Scott Norton wrote:

> Within a function I'm assigning dynamic variable names and values to them
> using the "assign" function.  I want to pass back the results but am
> uncertain how to do this.
>
>
>
> Basically, my function reads a number of data files and uses the filename of
> each file as the variable name for a list-to-become-dataframe.  I want then
> to pass all these lists back, but again, the names of the lists to pass back
> have been "assign-ed" to the filename.  See code snippet below, especially
> the "*** WHAT DO I PUT HERE ***" part!


This looks like a compromise between two strategies, either of which would
work on its own

1/ return a list of dataframes with tags based on the filenames
2/ create new variables with names based on the filenames.

The former approach is easy. The latter requires assigning into a
non-local environment, which is normally considered harmful but here is
the whole point of the command (as with R's load() function). You might
want to specify where the variables are to be created (as load() does).
I've written it below so that the default location is the calling
environment, and you would use loadFiles2(where=.GlobalEnv) to load into
the global environment.


So either

loadFiles1 <- function() {

  fullFileNames <- choose.files(filters = c("Fluor file (*.data,*.Dat)",
 "*.dat;*.Dat"))

  numFiles <- length(fullFileNames)

  fileNames <- basename(fullFileNames)
  splitNames <- strsplit(fileNames,"_")
  dfNames <- sapply(splitNames,"[",1)

  rval <-lapply(fullFileNames, ReadFileCreateDF)
  names(rval) <- dfNames

  return(rval)
 }

or

 loadFiles2 <- function(where=parent.frame()) {
    fullFileNames <- choose.files(filters = c("Fluor file (*.data,*.Dat)",
   "*.dat;*.Dat"))

  numFiles <- length(fullFileNames)

  fileNames <- basename(fullFileNames)
  splitNames <- strsplit(fileNames,"_")
  dfNames <- sapply(splitNames,"[",1)

  for (i in 1:numFiles)
     assign(dfNames[i], ReadFileCreateDF[i], envir=where)

  invisible(NULL)
 }




More information about the R-help mailing list