Home > Software engineering >  Partition a vector into chunks of equal sizes
Partition a vector into chunks of equal sizes

Time:05-02

I am trying to use R to partition a vector into equal groups.

An example is as follows. Suppose we have a vector x = c(1, 2, 3, 4, 5, 6), I want it to return all possible partitions of groups with 2 elements. One such example of a partition is {1, 2}, {3, 4}, {5, 6}.

Is there a way to do this in R? Some functions like expand.grid seems related but does not work for the purpose in this example.

The ideal output that I would like to have is a data.frame as follows. For each row, I can take the first 2 elements as the members of the first group, the next 2 elements as the members of the second group, and the last 2 elements as the members of the last group. The following is just two examples of all possible partitions. I'd like to have a data.frame that contains all possible partitions.

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    2    3    4    5    6    1
.....

Thanks!

CodePudding user response:

Are you looking for this?

all_chunks_size2 = function(x) {
   sapply(seq_len(length(x)), \(i) x[c(i, (i %% n 1))])
}

all_chunks_size2(x)
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    2    3    4    5    6
# [2,]    2    3    4    5    6    1

CodePudding user response:

x = c(1, 2, 3, 4, 5, 6)
result <- t(head(matrix(x[outer(seq_along(x) - 1, seq_along(x) - 1, ` `) %% length(x)   1],nrow = length(x)),6))
result
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    2    3    4    5    6    1
[3,]    3    4    5    6    1    2
[4,]    4    5    6    1    2    3
[5,]    5    6    1    2    3    4
[6,]    6    1    2    3    4    5
  •  Tags:  
  • r
  • Related