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

♀尐吖头ヾ 提交于 2019-12-20 20:31:15

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/7905456/in-r-how-do-i-get-all-possible-combinations-of-the-values-of-some-vectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!