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

后端 未结 1 1087
清歌不尽
清歌不尽 2021-02-08 18:13

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:

相关标签:
1条回答
  • 2021-02-08 18:28

    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
    
    0 讨论(0)
提交回复
热议问题