An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20111130/fb8f51b0/attachment.pl>
All combinations
3 messages · Alaios, michael.weylandt at gmail.com (R. Michael Weylandt, David Winsemius
expand.grid() This one is admittedly rather hard to find... Michael
On Nov 30, 2011, at 7:15 AM, Alaios <alaios at yahoo.com> wrote:
Dear all, I would like something simple to do in R that I do not know how I should search for it. Let's say that I have a list of a<-c(1,2,3,4,5) b<-(6,7,8) and I want to get back all their possible cominations like 1,6 1,7 1,8 2,6 2,7 2,8 3,6 3,7 3,8 and so on. How I can do that? B.R Alex [[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
On Nov 30, 2011, at 7:18 AM, R. Michael Weylandt wrote:
expand.grid() This one is admittedly rather hard to find...
Well, it is linked from the `combn` help page. And it is the likely to
be first or second in a search with ??combinations since it is in
pkg:base and at least on my interface the displayed hits are sorted by
alpha(pakgname), so I would disagree with it being hard to find.
Other ideas .... After replacing the missing `c` function:
> outer(a,b,FUN=paste, sep=",")
[,1] [,2] [,3]
[1,] "1,6" "1,7" "1,8"
[2,] "2,6" "2,7" "2,8"
[3,] "3,6" "3,7" "3,8"
[4,] "4,6" "4,7" "4,8"
[5,] "5,6" "5,7" "5,8"
Perhaps not what the OP asked for, but then exactly what did the OP
ask for, anyway?
Perhaps this? (Or not.)
> as.data.frame(sapply(a, function(x){ sapply(b, function(y)
c(x,y),simplify=FALSE)}) )
V1 V2 V3 V4 V5
1 1, 6 2, 6 3, 6 4, 6 5, 6
2 1, 7 2, 7 3, 7 4, 7 5, 7
3 1, 8 2, 8 3, 8 4, 8 5, 8
Interesting how print() handles data.frame columns of lists, don't you
think?
And then, of course, building it from scratch:
> matrix(c( rep(a, length(b)), rep(b, each=length(a))), ncol=2)
[,1] [,2]
[1,] 1 6
[2,] 2 6
[3,] 3 6
[4,] 4 6
[5,] 5 6
[6,] 1 7
[7,] 2 7
[8,] 3 7
[9,] 4 7
[10,] 5 7
[11,] 1 8
[12,] 2 8
[13,] 3 8
[14,] 4 8
[15,] 5 8
David. > > Michael > > On Nov 30, 2011, at 7:15 AM, Alaios <alaios at yahoo.com> wrote: > >> Dear all, >> I would like something simple to do in R that I do not know how I >> should search for it. >> >> Let's say that I have a list of >> a<-c(1,2,3,4,5) >> b<-(6,7,8) >> and I want to get back all their possible cominations like >> >> 1,6 >> 1,7 >> 1,8 >> 2,6 >> 2,7 >> 2,8 >> 3,6 >> 3,7 >> 3,8 >> and so on. >> >> How I can do that? >> >> B.R >> Alex David Winsemius, MD West Hartford, CT