[R] Splitting a data list into smaller data lists

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Wed Feb 15 07:37:19 CET 2012


Comments below.

On Tue, 14 Feb 2012, lawonga wrote:

> Hi, I am new at R and have been looking for a guide on how to do this with no
> avail. I have a data set similar to this:
>
> X   Y
> 1   2
> 3   3
> 4   9
> 2   4
> 6   3
> 9   1
> 1   7
> 0   2
> 5   6
> 3   8
>
> and I need it to be split into something like this:
>
> X   Y
> 1   2
> 3   3
> 4   9
> 2   4
> 6   3
>
> X  Y
> 9   1
> 1   7
> 0   2
> 5   6
> 3   8
>
> I am thinking I need to write a loop because my data set is much larger than
> this (1000) and I need it all organized into smaller data sets of 5's. Can
> someone point me in the write direction?

"Right" direction?

Type
   ?split
and
   ?":"
and
   ?"%/%"
and
   ?nrow
at the R command line

Read the "Introduction to R" (I2R) focusing on vector indexing.  Whenever 
possible you should prefer to use vector indexing instead of a for loop 
(there are certainly reasons to use for loops, but in most cases where 
they might be appropriate there are iterator functions like lapply that 
lead to more succinct and possibly faster code).

To use the resulting list, you will probably want to read
   ?lapply
and/or
   ?"[["

although the discussion of lists in I2R may be more digestible.

Depending on how you want to process data in the bigger picture, you may 
find the plyr package helpful.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k



More information about the R-help mailing list