胖鸭 2010-07-23 13:01
浏览 320

在 r 中将向量分割成块

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. So here is what I came up with, hopefully it helps someone some where.

x <- 1:10
n <- 3
chunk <- function(x,n) split(x, factor(sort(rank(x)%%n)))
chunk(x,n)
$`0`
[1] 1 2 3

$`1`
[1] 4 5 6 7

$`2`
[1]  8  9 10

Any comments, suggestions or improvements are really welcome and appreciated.

Cheers, Sebastian

转载于:https://stackoverflow.com/questions/3318333/split-a-vector-into-chunks-in-r

  • 写回答

18条回答 默认 最新

  • Memor.の 2010-07-23 14:22
    关注

    You could combine the split/cut, as suggested by mdsummer, with quantile to create even groups:

    split(x,cut(x,quantile(x,(0:n)/n), include.lowest=TRUE, labels=FALSE))
    

    This gives the same result for your example, but not for skewed variables.

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料