s-news
[Top] [All Lists]

Replicating the rows of a table n times each

To: <s-news@wubios.wustl.edu>
Subject: Replicating the rows of a table n times each
From: "Tzamouranis, Ioannis C" <Ioannis.Tzamouranis@constellation.com>
Date: Thu, 11 May 2006 07:52:22 -0400
Thread-index: AcZ08WQ02cBnCDhSQT2wHADN6dMX2w==
Thread-topic: Replicating the rows of a table n times each

Thanks to all the folks that pointed out easy ways to do this.

The question was:

Other than looping to produce this, is there a way to replicate the rows of a table n times each so that a table such as:

1 2 3 4

A B C D

5 6 7 8

a b c d

become

1 2 3 4

1 2 3 4

1 2 3 4

A B C D

A B C D

A B C D

5 6 7 8

5 6 7 8

5 6 7 8

a b c d

a b c d

a b c d

(where in this case n=3)?

For an answer, I quote Chris Green, although many others (Chris Baker, Christos Hatzis, Brad Biggerstaff and Thomas Jagger among them) gave equally good and similar answers:

Just use an index vector:

> z <- rbind(1:4,letters[1:4],5:8,upperCase(letters[1:4]))

> z

     [,1] [,2] [,3] [,4]

[1,] "1"  "2"  "3"  "4"

[2,] "a"  "b"  "c"  "d"

[3,] "5"  "6"  "7"  "8"

[4,] "A"  "B"  "C"  "D"

> z[rep(1:4,each=3),]

      [,1] [,2] [,3] [,4]

 [1,] "1"  "2"  "3"  "4"

 [2,] "1"  "2"  "3"  "4"

 [3,] "1"  "2"  "3"  "4"

 [4,] "a"  "b"  "c"  "d"

 [5,] "a"  "b"  "c"  "d"

 [6,] "a"  "b"  "c"  "d"

 [7,] "5"  "6"  "7"  "8"

 [8,] "5"  "6"  "7"  "8"

 [9,] "5"  "6"  "7"  "8"

[10,] "A"  "B"  "C"  "D"

[11,] "A"  "B"  "C"  "D"

[12,] "A"  "B"  "C"  "D"

The rep(1:4, each=3) expands to (1,1,1,2,2,2,3,3,3,4,4,4), so each row of the input will be repeated 3 times. Just change the "4" to the number of rows in the input (or nrow(z)) and the 3 to the number to times to replicate each row.


>>> This e-mail and any attachments are confidential, may contain legal,
professional or other privileged information, and are intended solely for the
addressee.  If you are not the intended recipient, do not use the information
in this e-mail in any way, delete this e-mail and notify the sender. CEG-IP2
<Prev in Thread] Current Thread [Next in Thread>