[R] how to split a data framed with sequences

jim holtman jholtman at gmail.com
Tue Sep 9 12:03:12 CEST 2008


Is this what you want:

> my.df <- data.frame(a = c(1:5, 1:10, 1:20), b = runif(35))
> split(my.df, c(0, cumsum(diff(my.df$a) < 0)))
$`0`
  a         b
1 1 0.2655087
2 2 0.3721239
3 3 0.5728534
4 4 0.9082078
5 5 0.2016819

$`1`
    a          b
6   1 0.89838968
7   2 0.94467527
8   3 0.66079779
9   4 0.62911404
10  5 0.06178627
11  6 0.20597457
12  7 0.17655675
13  8 0.68702285
14  9 0.38410372
15 10 0.76984142

$`2`
    a          b
16  1 0.49769924
17  2 0.71761851
18  3 0.99190609
19  4 0.38003518
20  5 0.77744522
21  6 0.93470523
22  7 0.21214252
23  8 0.65167377
24  9 0.12555510
25 10 0.26722067
26 11 0.38611409
27 12 0.01339033
28 13 0.38238796
29 14 0.86969085
30 15 0.34034900
31 16 0.48208012
32 17 0.59956583
33 18 0.49354131
34 19 0.18621760
35 20 0.82737332

>


On Tue, Sep 9, 2008 at 5:38 AM, David Carslaw
<d.c.carslaw at its.leeds.ac.uk> wrote:
>
> Hi all,
>
> Given a data frame:
>
> my.df <- data.frame(a = c(1:5, 1:10, 1:20), b = runif(35))
>
> I want to split it by "a" such that I end up with a list containing 3
> components i.e. the first containing a = 1 to 5, the second a = 1 to 10 etc.
> In other words, sets of sequences of a.
>
> I can't seem to find the right form using the split function - can you help?
>
> Much appreciated.
>
> David
>
>
>
> -----
> Institute for Transport Studies
> University of Leeds
> --
> View this message in context: http://www.nabble.com/how-to-split-a-data-framed-with-sequences-tp19388964p19388964.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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 that you are trying to solve?



More information about the R-help mailing list