[R] Splitting a data frame into several completely separate data frames

Gabor Grothendieck ggrothendieck at gmail.com
Sun Sep 26 18:42:28 CEST 2010


On Sun, Sep 26, 2010 at 8:52 AM, Josh B <joshb41 at yahoo.com> wrote:
> Hello again,
>
> How do I split a data frame into smaller, completely separate data frames
> (rather than separate data frames comprising a single "list")? Consider the
> following data, and my coding attempt:
>
> x <- read.table(textConnection("id type number
> indv.1 bagel 6
> indv.2 bagel 1
> indv.3 donuts 10
> indv.4 donuts 9"), header = TRUE)
> closeAllConnections()
>
> x.split <- split(x, x$type)
>
> This is where I'm stuck. Now I have one "list" comprised of different data
> frames, but what I want is separate data frames.
>
> Ideally, I'd like to design a loop to give sequentially-numbered names to the
> separate data frames I create. This is because my real data will have many more
> than two groups (i.e., many more types of things than just "bagels" versus
> "donuts") and the number of groups will vary when I apply the same code to
> different data sets.
>

Its normally better to keep them in a list but if you must:

> attach(x.split)
> bagel
      id  type number
1 indv.1 bagel      6
2 indv.2 bagel      1

Note that the attach puts the individual data frames in position 2 of
your search list and not in your workspace so its mainly useful if you
don't need to modify them. e.g. try this to see your search list:

search()

and this to list them:

> ls(2)
[1] "bagel"  "donuts"
>
> ls(as.environment("x.split"))
[1] "bagel"  "donuts"

If you want to be able to modify them or to have them directly in your
global workspace then use Uwe's answer.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list