Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This will split it differently to what you have, but is still quite a nice list structure I think:</p> <pre><code>chunk.2 &lt;- function(x, n, force.number.of.groups = TRUE, len = length(x), groups = trunc(len/n), overflow = len%%n) { if(force.number.of.groups) { f1 &lt;- as.character(sort(rep(1:n, groups))) f &lt;- as.character(c(f1, rep(n, overflow))) } else { f1 &lt;- as.character(sort(rep(1:groups, n))) f &lt;- as.character(c(f1, rep("overflow", overflow))) } g &lt;- split(x, f) if(force.number.of.groups) { g.names &lt;- names(g) g.names.ordered &lt;- as.character(sort(as.numeric(g.names))) } else { g.names &lt;- names(g[-length(g)]) g.names.ordered &lt;- as.character(sort(as.numeric(g.names))) g.names.ordered &lt;- c(g.names.ordered, "overflow") } return(g[g.names.ordered]) } </code></pre> <p>Which will give you the following, depending on how you want it formatted:</p> <pre><code>&gt; x &lt;- 1:10; n &lt;- 3 &gt; chunk.2(x, n, force.number.of.groups = FALSE) $`1` [1] 1 2 3 $`2` [1] 4 5 6 $`3` [1] 7 8 9 $overflow [1] 10 &gt; chunk.2(x, n, force.number.of.groups = TRUE) $`1` [1] 1 2 3 $`2` [1] 4 5 6 $`3` [1] 7 8 9 10 </code></pre> <p>Running a couple of timings using these settings:</p> <pre><code>set.seed(42) x &lt;- rnorm(1:1e7) n &lt;- 3 </code></pre> <p>Then we have the following results:</p> <pre><code>&gt; system.time(chunk(x, n)) # your function user system elapsed 29.500 0.620 30.125 &gt; system.time(chunk.2(x, n, force.number.of.groups = TRUE)) user system elapsed 5.360 0.300 5.663 </code></pre> <p>EDIT: Changing from as.factor() to as.character() in my function made it twice as fast.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload