R中多个向量的组合 [英] Combinations of multiple vectors in R

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

问题描述

我不确定置换是否是正确的词。我想给定一组n个向量(即 [1,2] [3,4] [2,3] )将它们全部置换并得到

I'm not sure if permutations is the correct word for this. I want to given a set of n vectors (i.e. [1,2],[3,4] and [2,3]) permute them all and get an output of

[1,3,2],[1,3,3],[1,4,2],[1,4,3],[2,3,2] etc.

R中是否有可以执行此操作的操作?

Is there an operation in R that will do this?

推荐答案

这是将向量存储在列表中并使用 do.call()为您安排适当的函数调用的有用情况。 expand.grid()是您想要的标准函数。但是,您不必键入或命名单个向量,请尝试:

This is a useful case for storing the vectors in a list and using do.call() to arrange for an appropriate function call for you. expand.grid() is the standard function you want. But so you don't have to type out or name individual vectors, try:

> l <- list(a = 1:2, b = 3:4, c = 2:3)
> do.call(expand.grid, l)
  a b c
1 1 3 2
2 2 3 2
3 1 4 2
4 2 4 2
5 1 3 3
6 2 3 3
7 1 4 3
8 2 4 3

但是,出于我的聪明,事实证明 expand.grid()接受列表:

However, for all my cleverness, it turns out that expand.grid() accepts a list:

> expand.grid(l)
  a b c
1 1 3 2
2 2 3 2
3 1 4 2
4 2 4 2
5 1 3 3
6 2 3 3
7 1 4 3
8 2 4 3

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

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