0

I have two numbers a=1.2 & b=0.9 and want to find out all possible combinations to arrange a&b in a vector with length 10. There has to be 5 elements of a and 5 elements of b in that vector. How can I write this in R? Many thanks!

 ideal output would be a matrix to all combinations:
 1. (a,b,a,b,a,b,a,b,a,b)
 2. (a,a,a,a,a,b,b,b,b,b)
 .
 .
 . 
user3446735
  • 125
  • 1
  • 3
  • 8

2 Answers2

2

I guess you could do:

x <- expand.grid(rep(list(c("a", "b")),10))
x <- x[rowSums(x == "a") == 5,]

head(x)
#   Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
#32    b    b    b    b    b    a    a    a    a     a
#48    b    b    b    b    a    b    a    a    a     a
#56    b    b    b    a    b    b    a    a    a     a
#60    b    b    a    b    b    b    a    a    a     a
#62    b    a    b    b    b    b    a    a    a     a
#63    a    b    b    b    b    b    a    a    a     a

But it would probably be less efficient than using a special package like combinat.

talat
  • 68,970
  • 21
  • 126
  • 157
1

You'll want to use the package combinat.

For example:

> library(combinat)
> try1 = ("a", "a", "b")
> permn(try1)
[[1]]
[1] "a" "a" "b"

[[2]]
[1] "a" "b" "a"

[[3]]
[1] "b" "a" "a"

[[4]]
[1] "b" "a" "a"

[[5]]
[1] "a" "b" "a"

[[6]]
[1] "a" "a" "b"

You could then manipulate this into a matrix. Your vector would just contain 5 a's and 5 b's.

Sarah
  • 731
  • 7
  • 15
  • Thanks for your quick response but is there any way to do it without installing new package? – user3446735 Oct 29 '14 at 22:57
  • 1
    Unless you explain why a installing a package creates a problem (and why you haven't upvoted a useful answer), most of us will assume you just want us to do your homework for a class (and that you don't abide by the conventions of SO.) – IRTFM Oct 30 '14 at 00:53