使用R获取总计为100的所有组合 [英] Getting all combinations which sum up to 100 using R

查看:56
本文介绍了使用R获取总计为100的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用8个变量获取总和等于100的所有组合,这些变量可以按10的增量步长从0到100取任意值(即0、10、20 ... 100)

I need to get all combinations for which the sum equal 100 using 8 variables that could take any value from 0 to 100 by incremental step of 10. (i.e. 0, 10, 20 ... 100)

下面的脚本可以做到这一点,但是效率很低,因为它创建了一个巨大的数据集,我想知道是否有人可以更好地做到这一点。

The following script does just that but is very inefficient as it creates a huge dataset and I was wondering if someone had a better way of doing this.

x <- expand.grid("ON" = seq (0,100,10), 
        "3M" = seq(0,100,10), 
        "6M" = seq(0,100,10), 
        "1Y" = seq(0,100,10), 
        "2Y" = seq(0,100,10),
        "5Y" = seq(0,100,10), 
        "10Y" = seq(0,100,10), 
        "15Y" = seq(0,100,10))

x <- x[rowSums(x)==100,]

编辑-

回答斯特凡·洛朗的问题

to answer the question from Stéphane Laurent

结果应该像

ON 3M 6M 1Y 2Y 5Y 10Y 15Y        
100 0  0  0  0  0   0   0  
 90 10  0  0  0  0   0   0  
 80 20  0  0  0  0   0   0  
 70 30  0  0  0  0   0   0  
 60 40  0  0  0  0   0   0  
 50 50  0  0  0  0   0   0

(...)

  0 0  0  0  0  0 10  90  
  0 0  0  0  0  0  0 100


推荐答案

在StéphaneLaurent的回答之后,我能够得到一个超快速的解决方案通过使用 uniqueperm2 函数此处

followed by Stéphane Laurent's answer, I am able to get a super fast solution by using the uniqueperm2 function here.

library(partitions)

C = t(restrictedparts(10,8))
do.call(rbind, lapply(1:nrow(C),function(i)uniqueperm2(C[i,])))

更新,使用 iterpc 包。

library(partitions)
library(iterpc)
C = t(restrictedparts(10,8))
do.call(rbind, lapply(1:nrow(C),function(i) getall(iterpc(table(C[i,]), order=T))))

速度大约是 uniqueperm2 的两倍

> f <- function(){
    do.call(rbind, lapply(1:nrow(C),function(i)uniqueperm2(C[i,])))
}
> g <- function(){
    do.call(rbind, lapply(1:nrow(C),function(i) getall(iterpc(table(C[i,]), order=T))))
}
> microbenchmark(f(),g())
Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval cld
  f() 36.37215 38.04941 40.43063 40.07220 42.29389 46.92574   100   b
  g() 16.77462 17.45665 19.46206 18.10101 20.65524 64.11858   100  a 

这篇关于使用R获取总计为100的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆