在R中,根据约束条件生成模型的所有可能解决方案 [英] In R, generating every possible solution to a model, based on constraints
问题描述
在R中,我试图生成一个矩阵,该矩阵显示模型的结果以及用于求解它们的值-所有这些均受约束.每种可能的解决方案.一个示例模型:
In R, I’m trying to generate a matrix that shows results from a model and the values used to solve them- all of which are constrained. Every possible solution. An example model:
Model = a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2
Model= a^2+b^2+c^2+d^2
位置:
20≤型号≤30
a = 1
2≤b≤3
2≤c≤3
3≤d≤4
我希望输出看起来像这样:
I’d like the output to look like this:
[a] [b] [c] [d] [Model]
[1] 1 3 2 3 23
[2] 1 2 2 4 25
[3] 1 3 3 3 28
[4] 1 2 3 3 23
顺序无关紧要.我只想要可行的[整数]值的完整排列.有什么包装或帮助您可以指明我的方向吗?
Order doesn't matter. I just want the full permutation of feasible [integer] values. Any packages or help you could point my way?
在我的示例情况下,我想基于设置的参数生成所有可能有效的输入(a,b,c,d).我只希望输出方程(模型)的值在20到30之间.在这种情况下,根据我设置的条件,只能有4个解.
In my example case, I want to generate all possible inputs(a,b,c,d) that hold valid, based on the parameters I set. I only want values from my output equation (Model) between 20 and 30. In this case, only 4 solutions are possible based on the criteria I'm setting.
推荐答案
假设您只在寻找整数解,则可以使用expand.grid()
Assuming you're only looking for integer solutions, you can use expand.grid()
dd <- expand.grid(a=1, b=2:3, c=2:3, d=3:4)
m <- with(dd, a^2+b^2+c^2+d^2)
inside <- function(x, a,b) a<=x & x<=b
cbind(dd, m)[inside(m, 20, 30),]
# a b c d m
# 2 1 3 2 3 23
# 3 1 2 3 3 23
# 4 1 3 3 3 28
# 5 1 2 2 4 25
# 6 1 3 2 4 30
# 7 1 2 3 4 30
(您说您想要的值是< = 30,但您的示例中似乎遗漏了30的值,可以更改要打开间隔的inside()
函数)
(you said you want values <=30 but you seem to have left out the 30's in your example, you can change the inside()
function of you want an open interval)
这篇关于在R中,根据约束条件生成模型的所有可能解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!