mateskabe
mateskabe

Reputation: 289

Split data frame based on group into list in defined order in R

I have simple data.frame

ts_df <- data.frame(val=c(20,30,40,50,21,26,11,41,47,41),
                cycle=c(3,3,3,3,2,2,2,1,1,1),
                date=as.Date(c("1985-06-30","1985-09-30","1985-12-31","1986-03-31","1986-06-30","1986-09-30","1986-12-31","1987-03-31","1987-06-30","1987-09-30")))

and I need split ts_df based on group but keep order inside resulted list based on date.

list_ts_df <- split(ts_df, ts_df$cycle)

So instead of

> list_ts_df
$`1`
   val cycle       date
8   41     1 1987-03-31
9   47     1 1987-06-30
10  41     1 1987-09-30

$`2`
  val cycle       date
5  21     2 1986-06-30
6  26     2 1986-09-30
7  11     2 1986-12-31

$`3`
  val cycle       date
1  20     3 1985-06-30
2  30     3 1985-09-30
3  40     3 1985-12-31
4  50     3 1986-03-31

I need desired output as

> list_ts_df
$`1`
  val cycle       date
1  20     3 1985-06-30
2  30     3 1985-09-30
3  40     3 1985-12-31
4  50     3 1986-03-31

$`2`
  val cycle       date
5  21     2 1986-06-30
6  26     2 1986-09-30
7  11     2 1986-12-31

$`3`
   val cycle       date
8   41     1 1987-03-31
9   47     1 1987-06-30
10  41     1 1987-09-30

Is there any simple solution how to achieve desired output? Thank you very much for any of your advises.

Upvotes: 1

Views: 483

Answers (1)

akrun
akrun

Reputation: 887148

We can do an order of the dataset first and then do the split on the 'cycle' by creating a factor with the levels specified as unique elements

t1 <- ts_df[order(ts_df$date),]
split(t1, factor(t1$cycle, levels = unique(t1$cycle)) )

Upvotes: 1

Related Questions