[R] expand.gird with constraints?

Berwin A Turlach Berwin.Turlach at gmail.com
Wed Aug 3 06:10:13 CEST 2011


G'day Kathie,

On Tue, 2 Aug 2011 19:56:00 -0700 (PDT)
Kathie <kathryn.lord2000 at gmail.com> wrote:

> Hi, R users,
> 
> Here is an example.
> 
> k <- c(1,2,3,4,5)
> i <- c(0,1,3,2,1)
> 
> if k=1, then j=0 from i
> if k=2, then j=0, 1 from i
> if k=3, then j=0, 1, 2, 3 from i
> if k=4, then j=0, 1, 2 from i
> if k=5, then j=0, 1 from i
> 
> so i'd like to create a list like below.
> 
> > list
>    k j
> 1  1 0
> 2  2 0
> 3  2 1
> 4  3 0
> 5  3 1
> 6  3 2
> 7  3 3
> 8  4 0
> 9  4 1
> 10 4 2
> 11 5 0
> 12 5 1
> 
> I tried expand.grid, but I can't.
> 
> Any suggestion will be greatly appreciated.

One possibility is:

R> k <- c(1,2,3,4,5)
R> i <- c(0,1,3,2,1)
R> tt <- c(1, 2, 4, 3, 2)
R> data.frame(k=rep(k, tt), j=unlist(sapply(tt, function(ii) i[1:ii])))
   k j
1  1 0
2  2 0
3  2 1
4  3 0
5  3 1
6  3 3
7  3 2
8  4 0
9  4 1
10 4 3
11 5 0
12 5 1

Not sure whether this is generalisable to your real problem...

HTH.

Cheers,

	Berwin

========================== Full address ============================
A/Prof Berwin A Turlach               Tel.: +61 (8) 6488 3338 (secr)
School of Maths and Stats (M019)            +61 (8) 6488 3383 (self)
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                     e-mail: Berwin.Turlach at gmail.com
Australia                http://www.maths.uwa.edu.au/~berwin
                         http://www.researcherid.com/rid/A-4995-2008



More information about the R-help mailing list