0

I have a dataframe:

> df <- data.frame(ID=c('1','1','1','1','1'), Type=c('a','a','b','c','c'), value=c(10,2,5,3,7))

  ID Type value
1  1    a    10
2  1    a     2
3  1    b     5
4  1    c     3
5  1    c     7

I want to split it into a list of subgroups, so that each subgroup will contain 2 Types.

So subgroup1 will have Type a and b

  ID Type value
1  1    a    10
2  1    a     2
3  1    b     5

and subgroup2 will have Type b and c

  ID Type value
3  1    b     5
4  1    c     3
5  1    c     7

and subgroup3 will have Type c and d ..... and so on

Is there any way to do that?

TYL
  • 1,577
  • 20
  • 33

2 Answers2

2

We can get the unique values in Type column and select rows from the dataframe 2 levels at a time.

uniq_lvls <- unique(df$Type)
lapply(seq_along(uniq_lvls)[-length(uniq_lvls)], function(x) 
                subset(df, Type %in% uniq_lvls[x:(x + 1)]))

#[[1]]
#  ID Type value
#1  1    a    10
#2  1    a     2
#3  1    b     5

#[[2]]
#  ID Type value
#3  1    b     5
#4  1    c     3
#5  1    c     7
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Here is a solution with base R to produce such kind of sub-groups, where split() and rbind() are used, i.e.,

subgrps <- lapply(seq(length(dfs <- split(df,df$Type))-1), 
              function(k) Reduce(rbind,dfs[k+0:1]))

such that

> subgrps
[[1]]
  ID Type value
1  1    a    10
2  1    a     2
3  1    b     5

[[2]]
  ID Type value
3  1    b     5
4  1    c     3
5  1    c     7
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81