Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将向量切分为块,使每个块的总和接近给定值_R - Fatal编程技术网

R 将向量切分为块,使每个块的总和接近给定值

R 将向量切分为块,使每个块的总和接近给定值,r,R,假设我们有一个向量x像 x <- c(9L, 4L, 7L, 1L, 2L, 13L, 7L, 11L, 14L, 2L, 11L, 3L, 1L, 5L, 5L, 10L, 6L, 14L, 10L, 7L) x也许您可以在while循环中使用cumsum尝试以下基本R选项 g <- 20 out <- c() while (length(x) > 0) { inds <- seq(max(which(cumsum(x) <= g))) out[

假设我们有一个向量
x

x <- c(9L, 4L, 7L, 1L, 2L, 13L, 7L, 11L, 14L, 2L, 11L, 3L, 1L, 5L, 
5L, 10L, 6L, 14L, 10L, 7L)

x也许您可以在
while
循环中使用
cumsum
尝试以下基本R选项

g <- 20
out <- c()
while (length(x) > 0) {
  inds <- seq(max(which(cumsum(x) <= g)))
  out[[length(out) + 1]] <- x[inds]
  x <- x[-inds]
}

也许您可以在
while
循环中使用
cumsum
尝试以下基本R选项

g <- 20
out <- c()
while (length(x) > 0) {
  inds <- seq(max(which(cumsum(x) <= g)))
  out[[length(out) + 1]] <- x[inds]
  x <- x[-inds]
}
基本R解决方案:

n <- 20
split(x, ceiling(cumsum(x) / n) * n)
nbaser解决方案:

n <- 20
split(x, ceiling(cumsum(x) / n) * n)
n可能重复可能重复