来自两个(或多个)向量的所有元素的唯一组合 [英] Unique combination of all elements from two (or more) vectors

查看:112
本文介绍了来自两个(或多个)向量的所有元素的唯一组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据R中两个大小不同的向量创建所有元素的唯一组合.

I am trying to create a unique combination of all elements from two vectors of different size in R.

例如,第一个向量是

a <- c("ABC", "DEF", "GHI")

第二个是当前存储为字符串的日期

and the second one is dates stored as strings currently

b <- c("2012-05-01", "2012-05-02", "2012-05-03", "2012-05-04", "2012-05-05")

我需要创建一个具有两列的数据框

I need to create a data frame with two columns like this

> data
    a          b
1  ABC 2012-05-01
2  ABC 2012-05-02
3  ABC 2012-05-03
4  ABC 2012-05-04
5  ABC 2012-05-05
6  DEF 2012-05-01
7  DEF 2012-05-02
8  DEF 2012-05-03
9  DEF 2012-05-04
10 DEF 2012-05-05
11 GHI 2012-05-01
12 GHI 2012-05-02
13 GHI 2012-05-03
14 GHI 2012-05-04
15 GHI 2012-05-05

因此,基本上,我正在通过考虑一个矢量(a)的所有元素与第二个矢量(b)的所有元素并置的方式来寻找一种独特的组合.

So basically, I am looking for a unique combination by considering all the elements of one vector (a) juxtaposed with all the elements of the second vector (b).

理想的解决方案将推广到更多的输入向量.

An ideal solution would generalize to more input vectors.

另请参见:
如何生成组合矩阵

See also:
How to generate a matrix of combinations

推荐答案

这也许是你所追求的

> expand.grid(a,b)
   Var1       Var2
1   ABC 2012-05-01
2   DEF 2012-05-01
3   GHI 2012-05-01
4   ABC 2012-05-02
5   DEF 2012-05-02
6   GHI 2012-05-02
7   ABC 2012-05-03
8   DEF 2012-05-03
9   GHI 2012-05-03
10  ABC 2012-05-04
11  DEF 2012-05-04
12  GHI 2012-05-04
13  ABC 2012-05-05
14  DEF 2012-05-05
15  GHI 2012-05-05

如果生成的订单不是您想要的,则可以随后进行排序.如果将参数命名为expand.grid,则它们将成为列名称:

If the resulting order isn't what you want, you can sort afterwards. If you name the arguments to expand.grid, they will become column names:

df = expand.grid(a = a, b = b)
df[order(df$a), ]

expand.grid可以归纳为任意数量的输入列.

And expand.grid generalizes to any number of input columns.

这篇关于来自两个(或多个)向量的所有元素的唯一组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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