Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I partition a vector?

Tags:

r

vector

How can I build a function

slice(x, n) 

which would return a list of vectors where each vector except maybe the last has size n, i.e.

slice(letters, 10)

would return

list(c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"),
     c("k", "l", "m", "n", "o", "p", "q", "r", "s", "t"),
     c("u", "v", "w", "x", "y", "z"))

?

like image 862
Karsten W. Avatar asked Mar 12 '10 18:03

Karsten W.


People also ask

How do I partition an array in C++?

Partition Array into Disjoint Intervals in C++ We have to find the length of left after such a partitioning. It is guaranteed that such a partitioning exists. So if the input is like [5,0,3,8,6], then the output will be 3, as left array will be [5,0,3] and right subarray will be [8,6].

Is there a partition function in C++?

C++ Algorithm partition() function is used to make partition the elements on the basis of given predicate (condition) mentioned in its arguments. If the container is partitioned then this function returns true, else returns false.

What is a partition in math?

In mathematics, a partition of a set is a grouping of its elements into non-empty subsets, in such a way that every element is included in exactly one subset.


2 Answers

slice<-function(x,n) {
    N<-length(x);
    lapply(seq(1,N,n),function(i) x[i:min(i+n-1,N)])
}
like image 88
Jyotirmoy Bhattacharya Avatar answered Sep 28 '22 22:09

Jyotirmoy Bhattacharya


You can use the split function:

split(letters, as.integer((seq_along(letters) - 1) / 10))

If you want to make this into a new function:

slice <- function(x, n) split(x, as.integer((seq_along(x) - 1) / n))
slice(letters, 10)
like image 41
Shane Avatar answered Sep 28 '22 22:09

Shane