[R] Passing a Data Frame Name as a Variable in a Function

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Thu Jan 29 07:34:46 CET 2015


This approach is fraught with dangers.

I recommend that you put all of those data frames into a list and have your function accept the list and the name and use the list indexing operator mylist[[DFName]] to refer to it. Having functions that go fishing around in the global environment will be hard to maintain at best, and buggy at worst.

That said, I usually work with all of my data frames combined as one and use the plyr, dplyr, or data.table packages to apply my algorithms to each group of rows identified by a character or factor column.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On January 28, 2015 5:37:34 PM PST, Alan Yong <alanyong at caltech.edu> wrote:
>Dear R-help,
>I have df.1001 as a data frame with rows & columns of values.
>
>I also have other data frames named similarly, i.e., df.*.
>
>I used DFName from:
>
>DFName <- ls(pattern = glob2rx("df.*"))[1]
>
>& would like to pass on DFName to another function, like:
>
>length(DFName[, 1])
>
>however, when I run:
>
>> length(DFName[, 1])
>Error in DFName[, 1] : incorrect number of dimensions
>
>and
>
>length(df.1001[, 1])
>[1] 104
>
>do not provide the same expected answer.
>
>How can I successfully pass the data frame name of df.1001 as a
>variable named DFName in a function?
>
>Thanks,
>Alan
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list