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.
The number of possible combinations is C(n,r)=n! r!
To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function.
The combn() function in R is used to return the combination of the elements of a given argument x taken m at a time.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With