rumtscho
rumtscho

Reputation: 2524

In R, how do I get all possible combinations of the values of some vectors?

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

A simplified example:

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"

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.

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.

Upvotes: 9

Views: 7855

Answers (1)

joran
joran

Reputation: 173697

I think you just want 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

Upvotes: 23

Related Questions