0

I am trying to dynamically split a list of numbers into separate vectord where they are in order.

Let’s say there are some vectord of numbers

Numbers_set1 <- c(53,54,55,56,58,59)
Numbers_set2 <- c(52,57)

I want to split them into different vectors depending on consecutive order like so

# so this is what each group would look like but done dynamically
Numbers_set1_group1 <- c(53,54,55,56)
Numbers_set1_group2 <- c(58,59)

Numbers_set2_group1 <- c(52)
Numbers_set2_group2 <- c(57)

I am trying to do this dynamically.

Another example


Numbers_set1 <- c(53,54,55,56,58,59,61,62,63)
Numbers_set2 <- c(52,57,60,64)

Numbers_set1_group1 <- c(53,54,55,56)
Numbers_set1_group2 <- c(58,59)
Numbers_set1_group3<- c(61,62,63)

Numbers_set2_group1 <- c(52)
Numbers_set2_group2 <- c(57)
Numbers_set2_group3<- c(60)
Numbers_set2_group4<- c(64)

There could be different amounts of vectors depending on how many numbers are in order.

Maybe specifying each sublist with i?

Thanks!

2 Answers2

0

You can use split with lapply:

Numbers_set1 <- c(53,54,55,56,58,59)
Numbers_set2 <- c(52,57)

lapply(list(Numbers_set1, Numbers_set2), \(x) split(x, cumsum(c(1, diff(x) != 1))))

If you want to replicate the names as well, you can use imap and lst, and then send the objects of the list to the Global environment with list2env.

library(tidyverse)
l <- imap(lst(Numbers_set1, Numbers_set2), 
         ~ split(.x,  paste0("group", cumsum(c(1, diff(.x) != 1)))))
l <- unlist(l, recursive = F)

l
#$Numbers_set1.group1
#[1] 53 54 55 56
#
#$Numbers_set1.group2
#[1] 58 59
#
#$Numbers_set2.group1
#[1] 52
#
#$Numbers_set2.group2
#[1] 57

list2env(l, envir = .GlobalEnv)
Maël
  • 45,206
  • 3
  • 29
  • 67
0

For the sake of completeness, the SplitAt() function from the DescTools package splits a vector into several pieces at given positions.

v <- c(53,54,55,56,58,59,61,62,63, 65)
l <- DescTools::SplitAt(v, which(diff(v) > 1) + 1)
l
[[1]]
[1] 53 54 55 56

[[2]]
[1] 58 59

[[3]]
[1] 61 62 63

[[4]]
[1] 65

As l is a list you can retrieve each sublist by it is index number, e.g.,

l[[3]]
[1] 61 62 63
Uwe
  • 41,420
  • 11
  • 90
  • 134