R all combinations of 3 vectors with conditions

假如想象 提交于 2019-12-13 07:34:37

问题


I have two vectors

vector1 = c(0.9,0.8,0.7,0.6,0.5)
vector2 = c(10,20,30)

I now want all combinations of the elements in these vectors, while vector2 is used twice. I use expand.grid() to this.

combinations = expand.grid(vector1,vector2,vector2)

The result is a frame with the columns Var1, Var2 and Var3.

Now I want to combine the first vector with the second vector with some conditions. E.g. 0.9 to 0.7 from vector1 should only be combined with Var2 >= Var3. And 0.6 to 0.5 should only be combined with Var2 <= Var3.

How can I do this?

This is an example. The real number of combinations is about 18,000 elements with 3 decimals. So I am also looking for an efficient way.


回答1:


Why not just generate your grid, then subset. For example,

co = expand.grid(vector1,vector2,vector2)
subset(co, (Var1 >= 0.7 & Var1 <= 0.9) & Var2 >= Var3  )


来源:https://stackoverflow.com/questions/22320766/r-all-combinations-of-3-vectors-with-conditions

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