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可能重复可能重复