简体   繁体   English

创建所有向量组合,总和最多等于R中的特定数字

[英]Create all vector combinations summing up to a specific number in R

I am trying to create a matrix with two combinations of the same vector that sum up to 2300. I am using the combn function in R, see the code below: 我正在尝试创建一个矩阵,其中两个矢量具有相同的组合,总和为2300。我在R中使用combn函数,请参见以下代码:

  vector <- 400:1900
  combinations <- combn(vector, 2, function(x) subset(x, sum(x)==2300))

Unfortunately, this code is not working. 不幸的是,此代码无法正常工作。 I get the following error: 我收到以下错误:

Error in combn(r2, 2, function(x) subset(x, sum(x) == 2300)) : 
  dims [product 1125750] do not match the length of object [0]

Do anyone know what i did wrong? 有人知道我做错了吗? Many thanks, 非常感谢,

Gion ion园

Try this: 尝试这个:

combinations <- combn(vector,2,function(x) ifelse(sum(x[1], x[2])==2300, 
list(c(x[1],x[2])), list(c(0,0))))

res <- combinations[lapply(combinations, sum)>0]

head(res)

# [[1]]
# [1]  400 1900

# [[2]]
# [1]  401 1899

# [[3]]
# [1]  402 1898

# [[4]]
# [1]  403 1897

# [[5]]
# [1]  404 1896

# [[6]]
# [1]  405 1895

If you want to get a matrix of that: 如果要获取该矩阵:

matrix(unlist(res), ncol = 2, byrow = TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM