这将分成不同的看法给你有什么,但仍是一个相当不错的表结构,我认为:
chunk.2 <- function(x, n, force.number.of.groups = TRUE, len = length(x), groups = trunc(len/n), overflow = len%%n) {
if(force.number.of.groups) {
f1 <- as.character(sort(rep(1:n, groups)))
f <- as.character(c(f1, rep(n, overflow)))
} else {
f1 <- as.character(sort(rep(1:groups, n)))
f <- as.character(c(f1, rep("overflow", overflow)))
}
g <- split(x, f)
if(force.number.of.groups) {
g.names <- names(g)
g.names.ordered <- as.character(sort(as.numeric(g.names)))
} else {
g.names <- names(g[-length(g)])
g.names.ordered <- as.character(sort(as.numeric(g.names)))
g.names.ordered <- c(g.names.ordered, "overflow")
}
return(g[g.names.ordered])
}
哪将根据你想要的格式给你以下内容:
> x <- 1:10; n <- 3
> 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
> 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
使用这些设置运行几个定时:
set.seed(42)
x <- rnorm(1:1e7)
n <- 3
然后我们有以下结果:
> system.time(chunk(x, n)) # your function
user system elapsed
29.500 0.620 30.125
> system.time(chunk.2(x, n, force.number.of.groups = TRUE))
user system elapsed
5.360 0.300 5.663
编辑:从as.factor改变()来as.character()在我的功能使得它快两倍。
是的,这是非常不清楚,你得到的是解决“大小相等的n个块”。但是,也许这也让你在那里:x < - 1:10; n < - 3; split(x,cut(x,n,labels = FALSE)) – mdsumner 2010-07-23 14:08:03
问题中的解决方案和前面的注释中的解决方案都不正确,因为如果向量具有重复条目,则它们可能无法正常工作。试试这个: > foo <-c(rep(1,12),rep(2,3),rep(3,3)) [1] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 3 3 3 >块(FOO,2) (给出错误的结果) >块(FOO,3) (也有错) – mathheadinclouds 2013-04-29 09:21:35
(继续前面的评论) 为什么呢? rank(x)不需要是整数 > rank(c(1,1,2,3)) [1] 1.5 1.5 3.0 4.0 所以这就是问题中的方法失败的原因。 (x,n)分割(x,cut(seq_along(x),n,labels = FALSE)) – mathheadinclouds 2013-04-29 09:33:14