# Re: [R] expand.grid() function

From: Gavin Simpson <gavin.simpson_at_ucl.ac.uk>
Date: Mon, 23 Jun 2008 14:51:05 +0100

On Mon, 2008-06-23 at 06:16 -0700, Megh Dal wrote:
> Hi,
>
> I have one question on expand.grid() function.
>
> When I write following syntax :expand.grid(c("u", "l"), c("u", "l"),
> c("u", "l")) I get following as desired :
> Var1 Var2 Var3
> 1 u u u
> 2 l u u
> 3 u l u
> 4 l l u
> 5 u u l
> 6 l u l
> 7 u l l
> 8 l l l
>
> However I wanted to write that in more concise manner. Therefore I
> tried : expand.grid(rep(c("u", "l"), 3)). But I did not get answer
> that I previously got. Can people here clarify me why it is not like
> that? Then what would be the mose concise way to do that?

In the first case, you have three vectors of length 2 as arguments to expand.grid, but in the second, you have a single vector of length 6. In the latter case, expand.grid can't expand a single vector, hence the single column result.

This is the closest I got to what you want:

as.matrix(expand.grid(split(rep(c("u","l"), times = 3),

factor(rep(1:3, each = 2)))))

Which gives:
> as.matrix(expand.grid(split(rep(c("u","l"), times = 3),
factor(rep(1:3, each = 2)))))

1 2 3

```[1,] "u" "u" "u"
[2,] "l" "u" "u"
[3,] "u" "l" "u"
[4,] "l" "l" "u"
[5,] "u" "u" "l"
[6,] "l" "u" "l"
[7,] "u" "l" "l"
[8,] "l" "l" "l"

```

But that isn't particularly concise...

HTH G

```--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help