In R, generating every possible solution to a model, based on constraints

瘦欲@ 提交于 2019-12-24 11:23:03

问题


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

Where:

20≤Model≤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?

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.


回答1:


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

(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)



来源:https://stackoverflow.com/questions/27606613/in-r-generating-every-possible-solution-to-a-model-based-on-constraints

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