[R] Variable variables using R ... e.g., looping over data frames with a numeric separator

Tony Plate taplate at gmail.com
Tue May 18 16:24:48 CEST 2010

On 05/17/2010 03:51 PM, Monte Shaffer wrote:
> for(i in 1:L-1)
> {
> dataStr = gsub(' ','',paste("fData.",i));
> dataVar = eval(dataStr);
>   ## GOAL is to grab data frame  'fData.1' and do stuff with it, then in next
> loop grab data frame 'fData.2' and do stuff with it
> }
As Dan Davison said, the more standard R way would be to put all your 
data frames in a list, then iterate over the list.

However, if do want to have your data frames in separate variables, and 
then get each data frame in a loop similar to the code fragment above, 
try something like this:

for (i in 1:(L-1)) {
     dataName <- paste("fData.", i, sep="")
     df <- get(dataName)
     ... do something with data frame df ...

You can also give additional arguments to get() to tell it where to look 
(pos=,envir=), and whether to look in parent environments 

-- Tony Plate

More information about the R-help mailing list