0

This seems to be a fairly simple problem but I can't find a simple solution:

I want to repeat a data.frame (i) several times as follows:

My initial data.frame:

   i <- data.frame(c("A","A","A","B","B","B","C","C","C"))
   i

Printing i results in:

   1  A
   2  A
   3  A
   4  B
   5  B
   6  B
   7  C
   8  C
   9  C

How I want to repeat the elements (The numbers on the first column is just for easy understanding/viewing)

   i 

  1  A
  2  A
  3  A
  4  B
  5  B
  6  B
  7  C
  8  C
  9  C
  1  A
  2  A
  3  A
  4  B
  5  B
  6  B
  7  C
  8  C
  9  C

I tried doing it using:

  i[rep(seq_len(nrow(i)), each=2),]

but it provides me output as such (The numbers on the first column is just for easy understanding/viewing):

  1  A
  2  A
  3  A
  1  A
  2  A
  3  A
  4  B
  5  B
  6  B
  4  B
  5  B
  6  B
  7  C
  8  C
  9  C
  7  C
  8  C
  9  C

Please help!

biobudhan
  • 289
  • 1
  • 2
  • 11
  • You may need `drop=FALSE` i.e. `i[rep(seq_len(nrow(i)), each=2),,drop=FALSE]` From the description, it is not clear what you wanted. Or may be you remove the `each` and use `times` i.e. `data.frame(i1=rep(i[,1],2))` – akrun Jul 21 '15 at 08:47
  • @Pascal: I did check the question, but that#s not exactly my problem. This is different! – biobudhan Jul 21 '15 at 08:51
  • 1
    @akrun: Great! data.frame(i1=rep(i[,1],2)) did solve my problem!! – biobudhan Jul 21 '15 at 08:53
  • This is a possible duplicate. –  Jul 21 '15 at 08:56
  • Oops. I just saw that @akrun was once again faster than me ;) Sorry, I didn't see your post prior to my edit. – RHertel Jul 21 '15 at 08:59

3 Answers3

2

Not sure if this solves your problem, but to obtain the desired output You could simply repeat the entire sequence:

 i <- c("A","A","A","B","B","B","C","C","C")
 i2 <- rep(i,2)
 #> i2
 # [1] "A" "A" "A" "B" "B" "B" "C" "C" "C" "A" "A" "A" "B" "B" "B" "C" "C" "C"

Since you're dealing with a data frame, you could use a slightly modified variant:

i <- data.frame(c("A","A","A","B","B","B","C","C","C")) 
i2 <- rep(i[,1],2)
RHertel
  • 23,412
  • 5
  • 38
  • 64
1

You could use rbind(i, i). Does that work?

CJB
  • 1,759
  • 17
  • 26
1

If you are working with a data frame, this code will work fine too:

i[rep(1:nrow(i), 5), ,drop=F]
Shahab Einabadi
  • 307
  • 4
  • 15