在R中,如何获得某些向量值的所有可能组合? [英] In R, how do I get all possible combinations of the values of some vectors?

查看:179
本文介绍了在R中,如何获得某些向量值的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我有一个带有一些参数的函数。我想要所有可能的参数组合的函数结果。

The background: I have a function which takes some parameters. I want to have the result of the function for all possible parameter combinations.

一个简化的示例:

f <- function(x, y) { return paste(x, y, sep=",")} 
colors = c("red", "green", "blue") 
days = c("Monday", "Tuesday") 

我希望我的结果看起来像

I want my result to look like

     color    day         f    
[1,] "red"    "Monday"    "red,Monday" 
[2,] "red"    "Tuesday"   "red,Tuesday"
[3,] "green"  "Monday"    "green,Monday"
[4,] "green"  "Tuesday"   "green,Tuesday"
[5,] "blue"   "Monday"    "blue,Monday"
[6,] "blue"   "Tuesday"   "blue,Tuesday"

我的想法是用列 color day 创建一个矩阵,使用现有的矢量颜色填充它,为结果初始化一个空列,然后使用循环调用f每个矩阵行一次,并将结果写入最后一列。但是我不知道如何轻松地从颜色 days 向量生成矩阵。我尝试搜索它,但是得到的所有结果都是 combn 函数的,它的功能有所不同。

My idea is to create a matrix with the columns color and day, fill it using the existing vectors colors and days, initialize an empty column for the results, then use a loop to call f once per matrix row and write the result into the last column. But I don't know how to easily generate the matrix from the colors and days vector. I tried searching for it, but all results I got were for the combn function, which does something different.

在这种简化的情况下,颜色是因素,但在我的真实示例中,情况并非如此。该函数的一些参数是整数,因此我的真实向量可能更像 1、2、3 ,并且该函数将要求将其作为数字传递给它。因此,请不要使用依赖因子水平的解决方案(如果它们不能以某种方式用于整数)。

In this simplified case, the colors and days are factors, but in my real example, this is not the case. Some of the parameters to the function are integers, so my real vector may look more like 1, 2, 3 and the function will require that it is passed to it as numeric. So please no solutions which rely on factor levels, if they can't somehow be used to work with integers.

推荐答案

我认为您只需要 expand.grid

> colors = c("red", "green", "blue") 
> days = c("Monday", "Tuesday") 
> expand.grid(colors,days)
   Var1    Var2
1   red  Monday
2 green  Monday
3  blue  Monday
4   red Tuesday
5 green Tuesday
6  blue Tuesday

并且,如果您想在同一行中指定列名:

And, if you want to specify the column names in the same line:

> expand.grid(color = colors, day = days)
  color     day
1   red  Monday
2 green  Monday
3  blue  Monday
4   red Tuesday
5 green Tuesday
6  blue Tuesday

这篇关于在R中,如何获得某些向量值的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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