StudentOfScience
StudentOfScience

Reputation: 809

R: Matrix of n columns with every combination of 2 items

I want a matrix, that is n columns long.

n <- 3

the combination i want is 1 and -1

c <- c(1,-1)

that gives the number of rows as:

r <- 2^n

and so you would make a matrix of 0 with these dims as such:

mm <- matrix(0, r, n)

Now, how do I fill it with 1s and -1s. of every combination. if n = 2 we should get:

{(1,1), (1,-1), (-1, 1), (-1, -1)}

and so on.

Whats the best way to achieve this?

Upvotes: 0

Views: 328

Answers (1)

Jake Burkhead
Jake Burkhead

Reputation: 6545

n <- 2
x <- c(-1, 1)
expand.grid(rep(list(x), n))

##    Var1 Var2
## 1   -1   -1
## 2    1   -1
## 3   -1    1
## 4    1    1

n <- 3
expand.grid(rep(list(x), n))

##   Var1 Var2 Var3
## 1   -1   -1   -1
## 2    1   -1   -1
## 3   -1    1   -1
## 4    1    1   -1
## 5   -1   -1    1
## 6    1   -1    1
## 7   -1    1    1
## 8    1    1    1

Upvotes: 1

Related Questions