Split a vector into chunks

后端 未结 20 1897
时光说笑
时光说笑 2020-11-22 01:10

I have to split a vector into n chunks of equal size in R. I couldn\'t find any base function to do that. Also Google didn\'t get me anywhere. Here is what I came up with so

相关标签:
20条回答
  • 2020-11-22 02:12

    Here's another variant.

    NOTE: with this sample you're specifying the CHUNK SIZE in the second parameter

    1. all chunks are uniform, except for the last;
    2. the last will at worst be smaller, never bigger than the chunk size.

    chunk <- function(x,n)
    {
        f <- sort(rep(1:(trunc(length(x)/n)+1),n))[1:length(x)]
        return(split(x,f))
    }
    
    #Test
    n<-c(1,2,3,4,5,6,7,8,9,10,11)
    
    c<-chunk(n,5)
    
    q<-lapply(c, function(r) cat(r,sep=",",collapse="|") )
    #output
    1,2,3,4,5,|6,7,8,9,10,|11,|
    
    0 讨论(0)
  • 2020-11-22 02:12

    I needed the same function and have read the previous solutions, however i also needed to have the unbalanced chunk to be at the end i.e if i have 10 elements to split them into vectors of 3 each, then my result should have vectors with 3,3,4 elements respectively. So i used the following (i left the code unoptimised for readability, otherwise no need to have many variables):

    chunk <- function(x,n){
      numOfVectors <- floor(length(x)/n)
      elementsPerVector <- c(rep(n,numOfVectors-1),n+length(x) %% n)
      elemDistPerVector <- rep(1:numOfVectors,elementsPerVector)
      split(x,factor(elemDistPerVector))
    }
    set.seed(1)
    x <- rnorm(10)
    n <- 3
    chunk(x,n)
    $`1`
    [1] -0.6264538  0.1836433 -0.8356286
    
    $`2`
    [1]  1.5952808  0.3295078 -0.8204684
    
    $`3`
    [1]  0.4874291  0.7383247  0.5757814 -0.3053884
    
    0 讨论(0)
提交回复
热议问题