Reputation: 139
I am trying to create an data frame that is generated from combinations of a list of character strings in R. For example, the list would be something like
list <- c("liz", "doug", "stacy")
The end output goal would be a data frame that would have rows that allow for each combination to be present, such as this:
df <- as.data.frame(cbind(c("liz", "liz", "doug"), c("doug", "stacy", "stacy")))
I'm trying to make so that each pair is it's own row, with no repeated combinations. Any thoughts on how to achieve this with larger character lists?
Thanks in advance.
Upvotes: 2
Views: 356
Reputation: 9858
expand.grid()
will give you all the possible combinations of its vector arguments:
number_of_variables<-2
output<-expand.grid(data.frame(replicate(number_of_variables, list))
>output
X1 X2
1 liz liz
2 doug liz
3 stacy liz
4 liz doug
5 doug doug
6 stacy doug
7 liz stacy
8 doug stacy
9 stacy stacy
To have every combination as a column call transpose(output)
If you want unique combinations (discard those with the same elements), use combn()
:
> data.frame(combn(list, number_of_variables))
X1 X2 X3
1 liz liz doug
2 doug stacy stacy
Upvotes: 2