[R] Creating dataframe names on the fly?

Paul Johnson pauljohn32 at gmail.com
Sat Mar 21 07:15:04 CET 2009


On Fri, Mar 20, 2009 at 7:18 PM, science! <karthik.ram at gmail.com> wrote:
>
> I am aware that it is easily possible to create var names on the fly. e.g.
> assign(paste("m",i,sep=""),j)
> but is it possible to assign dataframes to variables created on the fly?
>
> e.g.
> If I have a dataframe called master and I wanted to subset parts of those
> data into separate dataframes, I could do:
>
> m1=subset(master,master$SAMPLE=='1')
> m2=subset(master,master$SAMPLE=='2')
> .....
>
> but I would like to do this in a loop. Can someone give me suggestions on
> how to accomplish this?
>
>
> I tried assign(paste("m",i,sep=""),subset(master,master$SAMPLE==i) with no
> success.
>
Are you sure you really need to name these dataframes?

Here's a workaround that I use for these cases.  Create your new data
frames and add them to a list, as in

myframes <- list(subset(master,master$SAMPLE=='1'),
m2=subset(master,master$SAMPLE=='2'))

Then when you want to use these things,  you can get the first one as
myframes[[1]]
or myframes[[2]].

You can name the objects inside the list:

names(myframes) <- c("A","B")

This is just as good as referring to them  by name, in my experience.
It also has the benefit that because your dataframes are in a list,
then you can use features like lapply to do things for each dataset.

I'm reading ?assign now, and it appears  you can actually name these things.

> name <- paste("fred",4,sep="")
> x <- data.frame(py=rnorm(10))
> assign(name,x)
> ls()
[1] "fred4" "mname" "name"  "x"
> name
[1] "fred4"
> fred4
            py
1  -1.04243477
2  -0.66475049
3  -0.08576428
4   0.64369356
5  -0.06828696
6   1.15710627
7  -2.45041700
8   0.40139655
9   0.27320936
10 -0.98028020

pj



-- 
Paul E. Johnson
Professor, Political Science
1541 Lilac Lane, Room 504
University of Kansas




More information about the R-help mailing list