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

jim holtman jholtman at gmail.com
Sun Aug 19 23:22:24 CEST 2007


One way to do it is to pass in the character name of the dataframe you
want to reference and then use 'get' to access the value: e.g.,

df1 <- data.frame(x=seq(0,10), y=seq(10,20))
df2 <- data.frame(a=seq(0,10), b=seq(10,20))
# use the character names for referencing
for (df in c('df1', 'df2')){
    # get the data to operate on (read-only)
    .val <- get(df)
    # now you can reference the object
    print(names(.val))
    # or construct new objects to store the value in
    # or you can use "assign' to store back in the original object
    assign(paste('temp.', df, sep=''), .val)
}


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.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list