问题
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