On Mon, Mar 21, 2011 at 04:08:50AM -0700, Julio Rojas
wrote:> Dear all, I have three vectors "x<-1:n", "y<-1:m"
and "z<-2:(n+m)". I need to find all combinations of "x"
and "y" that add up a given value of "z", e.g., for
"z==3" the combinations will be "list(c(1,2),c(2,1))".
Dear Julio:
Try the following.
n <- 3
m <- 4
x <- 1:n
y <- 1:m
a <- expand.grid(x=x, y=y)
b <- subset(a, x + y == 3)
b
x y
2 2 1
4 1 2
In order to create a list of the required pairs, try
the following
out <- vector("list", nrow(b))
for (i in seq.int(along=out)) {
out[[i]] <- c(b[i, 1], b[i, 2])
}
Hope this helps.
Petr Savicky.