user1359552
user1359552

Reputation: 1

Generate vectors using R

I would like to ask,if some of You dont know any simple way to solve this kind of problem: I need to generate all combinations of A numbers taken from a set B (0,1,2...B), with their sum = C.

ie if A=2, B=3, C=2:

Solution in this case:

(1,1);(0,2);(2,0)

So the vectors are length 2 (A), sum of all its items is 2 (C), possible values for each of vectors elements come from the set {0,1,2,3} (maximum is B).

Upvotes: 0

Views: 406

Answers (3)

Josh O'Brien
Josh O'Brien

Reputation: 162321

Using the nifty partitions() package, and more interesting values of A, B, and C:

library(partitions)

A <- 2
B <- 5
C <- 7

comps <- t(compositions(C, A))
ii <- apply(comps, 1, FUN=function(X) all(X %in% 0:B))
comps[ii, ]
#      [,1] [,2]
# [1,]    5    2
# [2,]    4    3
# [3,]    3    4
# [4,]    2    5

Upvotes: 1

IRTFM
IRTFM

Reputation: 263301

z <- expand.grid(0:3,0:3)
z[rowSums(z)==2, ]
  Var1 Var2
3    2    0
5    1    1
7    0    2

If you wanted to do the expand grid programmatically this would work:

z <- expand.grid( rep( list(C), A) )

You need to expand as a list so that the items remain separate. rep(0:3, 3) would not return 3 separate sequences. So for A=3:

> z <- expand.grid(rep(list(0:3), 3))
> z[rowSums(z)==2, ]
   Var1 Var2 Var3
3     2    0    0
6     1    1    0
9     0    2    0
18    1    0    1
21    0    1    1
33    0    0    2

Upvotes: 1

Justin
Justin

Reputation: 43245

A functional version since I already started before SO updated:

A=2
B=3
C=2

myfun <- function(a=A, b=B, c=C) {
  out <- do.call(expand.grid, lapply(1:a, function(x) 0:b))
  return(out[rowSums(out)==c,])
}

> out[rowSums(out)==c,]
  Var1 Var2
3    2    0
6    1    1
9    0    2

Upvotes: 1

Related Questions