R:获得三个数字的所有组合加起来为100 [英] R: get all combinations of three numbers that add up to 100
本文介绍了R:获得三个数字的所有组合加起来为100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个变量:X,Y和Z.我想找到X,Y和Z的所有组合加起来等于100.X,Y和Z只能取[0,100]之间的值.输出看起来应该像这样:
I have three variables: X, Y, and Z. I want to find all the combinations of X, Y and Z that add up to 100. X, Y and Z can only take values between [0,100]. The ouput should look somehtinkg like this:
X Y Z Sum
100 0 0 100
99 1 0 100
99 0 1 100
98 2 0 100
98 1 1 100
98 0 2 100
以此类推...
关于如何获得所有可能组合的任何建议?
Any suggestion on how to get all the possible combinations?
推荐答案
由于只有三列限制为1:100,因此这很容易造成暴力.如果范围更大,将需要一个更聪明的解决方案.
Since you're limited to 1:100 on only three columns, this is easy to brute force. Would need a more clever solution if the range was larger.
library(data.table)
df <- expand.grid(X = 0:100,
Y = 0:100,
Z = 0:100)
setDT(df)
df[, Sum := X + Y + Z]
df[Sum == 100]
# X Y Z Sum
# 1: 100 0 0 100
# 2: 99 1 0 100
# 3: 98 2 0 100
# 4: 97 3 0 100
# 5: 96 4 0 100
# ---
# 5147: 1 1 98 100
# 5148: 0 2 98 100
# 5149: 1 0 99 100
# 5150: 0 1 99 100
# 5151: 0 0 100 100
这篇关于R:获得三个数字的所有组合加起来为100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文