[R] returning dynamic variable names from function

Roger D. Peng rpeng at jhsph.edu
Thu Oct 16 18:31:48 CEST 2003


One thing you could do the assign() directly into the global workspace, i.e.

assign(dfNames[[i]],ReadFileCreateDF(fullFileNames[[i]]), envir = globalenv())

-roger



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! 
>
> 
>
>Thanks in advance for any help!!!
>
>
>
>-Scott
>
> 
>
> 
>
>CODE SNIPPET BELOW:
>
> 
>
>loadFiles <- function()
>
>{
>
> 
>
> fullFileNames <- choose.files(filters = c("Fluor file (*.data,*.Dat)",
>"*.dat;*.Dat"))
>
> numFiles <- length(fullFileNames)
>
> fileNames <- basename(fullFileNames)   # removes the all the paths from the
>full filenames
>
> splitNames <- strsplit(fileNames,"_")    # create a "list" of strings
>separated by the "_" character
>
> 
>
> dfNames <- sapply(splitNames,"[",1)
>
> # or I could use  "sapply(splitNames, function (x) x[1])"   OR EVEN
>"unlist(lapply(splitNames, function(x)x[1]))"   -- [Thanks to Andy Liaw,
>Simon Blomberg, Gabor Grothendieck, 
>
> #James Holtman and Robert Keefe for their helpful responses on this
>question - See posting on returning the first elements of a list of vectors]
>
> # 
>
> 
>
> for (i in 1:numFiles)
>
>     {
>
>     assign(dfNames[[i]],ReadFileCreateDF(fullFileNames[[i]]))
># we use "assign" since we want the quoted string in dfNames to be assigned
>the value of the function call
>
>               # the ReadFileCreateList is a function that reads an
>individual file and sends back a number of parameters in a list
>
>     }
>
> return(list( *** WHAT DO I PUT HERE***))
>
> }
>
> 
>
> 
>
>Scott Norton, Ph.D.
>
>Engineering Manager
>
>Nanoplex Technologies, Inc.
>
>2375 Garcia Ave.
>
>Mountain View, CA 94043
>
>www.nanoplextech.com
>
> 
>
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>  
>




More information about the R-help mailing list