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"))
?
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].
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.
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.
slice<-function(x,n) {
N<-length(x);
lapply(seq(1,N,n),function(i) x[i:min(i+n-1,N)])
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With