R: get all combinations of three numbers that add up to 100

半世苍凉 提交于 2021-01-27 18:12:17

问题


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

and so on...

Any suggestion on how to get all the possible combinations?


回答1:


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



回答2:


An alternative (perhaps more efficient for large numbers) would be

df <- do.call(rbind, lapply(0:100, function(i) data.frame(x=i, y=0:(100-i))))
df$z <- 100-df$x-df$y


来源:https://stackoverflow.com/questions/46778078/r-get-all-combinations-of-three-numbers-that-add-up-to-100

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!