Split a vector into chunks

后端 未结 20 1943
时光说笑
时光说笑 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:04

    Try the ggplot2 function, cut_number:

    library(ggplot2)
    x <- 1:10
    n <- 3
    cut_number(x, n) # labels = FALSE if you just want an integer result
    #>  [1] [1,4]  [1,4]  [1,4]  [1,4]  (4,7]  (4,7]  (4,7]  (7,10] (7,10] (7,10]
    #> Levels: [1,4] (4,7] (7,10]
    
    # if you want it split into a list:
    split(x, cut_number(x, n))
    #> $`[1,4]`
    #> [1] 1 2 3 4
    #> 
    #> $`(4,7]`
    #> [1] 5 6 7
    #> 
    #> $`(7,10]`
    #> [1]  8  9 10
    

提交回复
热议问题