不同向量的组合 [英] combination from different vectors

查看:106
本文介绍了不同向量的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的向量

V1 = c(1,2,3,4,5)
V2 = c(7,8,9,10,11)
V3 = c(15,16,17,18,19)
V4 = c(3,4,5,6,7)

我想从这些向量中获得所有可能的组合,它们看起来像这样 [V1 [i],V2 [j],V3 [k],v4 [z]] ,总计为3 + 9 + 17 + 5。
这与重复的 R:sample()命令有点不同受约束,因为我想从每个向量中获取一个元素的所有组合,而不是从一个向量中获取所有组合。可能的解决方案应该是每个向量都有一个元素。

I would like to get all possible combinations from these vectors that look like this [V1[i],V2[j],V3[k],v4[z]] and that sums up to 3+9+17+5. This is a bit different from the duplicate R: sample() command subject to a constraint because I would like to get all combinations with one element from each vector and not get all combination from one vector. A possible solution should have one element from each vector.

例如,以下是解决方案

[1,11,17,5] 
[2,8,18,6]
[5,9,15,5] 
[3,11,16,3]

等等。解决方案可以有重复的值,这很好。

and many others are. The solutions can have duplicated values which is fine.

关于如何在R中实现此功能的任何想法?我是R语言的初学者,希望能得到一些答案。

Any ideas on how to implement this in R? I am a beginner in R and I hope really to get some answers.

推荐答案

如果我正确理解了您的问题,则可能是在寻找 expand.grid

If I understand your questions correctly, you are probably looking for expand.grid:

> expand.grid( V1=V1, V2=V2, V3=V3, V4=V4 )[1:5,]
  V1 V2 V3 V4
1  1  7 15  3
2  2  7 15  3
3  3  7 15  3
4  4  7 15  3
5  5  7 15  3
...

这将产生所有data.frame,每个组合一行一行

This will yield all a data.frame with one row per combination

这篇关于不同向量的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆