Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
rumtscho Avatar asked Oct 26 '11 16:10

rumtscho


People also ask

How do you find the number of combinations in R?

The number of possible combinations is C(n,r)=n! r!

How do I find unique combinations in R?

To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function.

What does Combn function in R do?

The combn() function in R is used to return the combination of the elements of a given argument x taken m at a time.

What does expand grid do in R?

expand. grid() function in R Language is used to create a data frame with all the values that can be formed with the combinations of all the vectors or factors passed to the function as argument.


1 Answers

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
like image 66
joran Avatar answered Oct 16 '22 03:10

joran