R 创建一组不超过34的数字

R 创建一组不超过34的数字,r,R,我需要创建一组数字,这些数字的总和不能达到34 例如:我有一个数组x,假设您需要满足此条件的x子集的所有可能组合,您可以使用 x = c(28,26,20,5,3,2,1) y = lapply(seq_along(x), function(y) combn(x, y)) # list all combinations of all subsets le34 = sapply(y, function(z) colSums(z) <= 34) # which sums are less th

我需要创建一组数字,这些数字的总和不能达到34


例如:我有一个数组
x,假设您需要满足此条件的x子集的所有可能组合,您可以使用

x = c(28,26,20,5,3,2,1)
y = lapply(seq_along(x), function(y) combn(x, y)) # list all combinations of all subsets
le34 = sapply(y, function(z) colSums(z) <= 34) # which sums are less than 34
lapply(seq_along(y), function(i) y[[i]][,le34[[i]]] ) # list of combinations that meet condition
x=c(28,26,20,5,3,2,1)
y=lappy(沿(x)的顺序,函数(y)组合(x,y))#列出所有子集的所有组合

le34=sapply(y,函数(z)colSums(z)如果我理解正确,这就是您想要做的:

create_groups <- function(input, threshold) {
  input <- sort(input, decreasing = TRUE)
  result <- vector("list", length(input))
  sums <- rep(0, length(input))
  for (k in input) {
    i <- match(TRUE, sums + k <= threshold)
    if (!is.na(i)) {
      result[[i]] <- c(result[[i]], k)
      sums[i] <- sums[i] + k
    }
  }
  result[sapply(result, is.null)] <- NULL
  result
}

create_groups(x, 34)
# [[1]]
# [1] 28  5  1
#
# [[2]]
# [1] 26  3  2
#
# [[3]]
# [1] 20

创建组以及为什么创建这些特定组?组(28)(26)(20)(5)(3)(2)(1)也不要超过34。我们有最小和最大组大小吗?@Dason。因为我必须创建尽可能少的不超过34的组。因此我必须在脚本中实现的过程是:1.按降序排序数组2.我取数组中的最大数3.我将其添加到下一个数组中4.如果总和大于34,我将尝试添加第三个元素,以此类推。但是,如果总和小于34,我必须添加第三个元素,因为总和可能仍然小于34。脚本的理念是创建尽可能少的组数,但不超过3434@MatteoBertazzoni我的意思是,你在最初的问题中没有具体说明这一点。我们不是你,所以我如果您不告诉我们规格,那么我们就不知道。请修改您的问题,以概述所有要求。如果您想要最小数量的组,则称为。此处可能有关联。
y <- c(18, 15, 11, 9, 8, 7)
create_groups(y, 34)
# [[1]]
# [1] 18 15
# 
# [[2]]
# [1] 11  9  8
# 
# [[3]]
# [1] 7