Split a vector into chunks

后端 未结 20 2146
时光说笑
时光说笑 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 01:55

    I have come up with this solution:

    require(magrittr)
    create.chunks <- function(x, elements.per.chunk){
        # plain R version
        # split(x, rep(seq_along(x), each = elements.per.chunk)[seq_along(x)])
        # magrittr version - because that's what people use now
        x %>% seq_along %>% rep(., each = elements.per.chunk) %>% extract(seq_along(x)) %>% split(x, .) 
    }
    create.chunks(letters[1:10], 3)
    $`1`
    [1] "a" "b" "c"
    
    $`2`
    [1] "d" "e" "f"
    
    $`3`
    [1] "g" "h" "i"
    
    $`4`
    [1] "j"
    

    The key is to use the seq(each = chunk.size) parameter so make it work. Using seq_along acts like rank(x) in my previous solution, but is actually able to produce the correct result with duplicated entries.

提交回复
热议问题