[R] How to parse a string into the symbol for a data frame object

Gabor Grothendieck ggrothendieck at gmail.com
Mon Aug 20 03:09:23 CEST 2007

You might want to store the data frames in a list to eliminate this
problem and make it more convenient to iterate over them:

L <- list(df1 = df1, df2 = df2)
rm(df1, df2)

# reduce each data frame to its first few rows
for(nm in names(L))   L[[nm]] <- head(L[[nm])

or if you don't need to modify them or know their names:

# print first few lines of each
for(df in L) print(head(df))

On 8/19/07, Darren Weber <darren.weber.lists at gmail.com> wrote:
>  I have several data frames, eg:
> > df1 <- data.frame(x=seq(0,10), y=seq(10,20))
> > df2 <- data.frame(a=seq(0,10), b=seq(10,20))
> It is common to create loops in R like this:
> > for(df in list(df1, df2)){ #etc. }
> This works fine when you know the name of the objects to put into the
> list.  I assume that the order of the objects in the list is respected
> through the loop.  Inside the loop, the objects of the list are
> 'dereferenced' using 'df' but, to my knowledge, there is no way to
> tell whether 'df' is a current representation of 'df1' or 'df2'
> without some additional book keeping.
> In addition, I really want to use 'paste' within the loop to create a
> new string value that will have the symbol name of a data frame to be
> "dereferenced," e.g.:
> > for(n in c(1, 2)){ dfString <- paste('df', n, sep=""); print(eval(dfString)) }
> [1] "df1"
> [1] "df2"
> This is not what I want.  I have read through the documentation on
> eval and similar commands like substitute and quote.  I program
> regularly, but I do not understand these constructs in R.  I do not
> understand the R framework for parsing and evaluation and I don't have
> a lot of time right now to get lost in this detail.  I could really
> use some help to get the string values in my loop to be parsed into
> symbols that refer to the data frame objects df1 and df2.  How is this
> done?
> Best, Darren
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> 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