0

I'd like to understand the syntax for elegantly asking R to populate repetitive numbers in a data frame.

I need to count from 1 to 256 64 * 3 times, which I found straightforward enough.

df$Address<-rep(1:256,192)

I need a column to repeat a 1 256*64 rows, then repeat a 3 256*64 rows, then repeat a 5 256*64 rows. I found that one to be intuitive.

df$Gain<-c(rep(1,256*64),rep(3,256*64),rep(5,256*64))

But I can't seem to grasp the syntax for needing to repeat 1 256 times, then 2 256 times, then 3 256 times up to 64 256 times, all 3 times. I wanted something like this to work, but it doesn't:

df$Ref<-rep(rep(1,256):64*3)

What's an elegant way to repeat a number 256 times and then increment that number and repeat?

chrysrobyn
  • 73
  • 1
  • 10
  • 1
    `rep(1:64, each = 256)` – Gregor Thomas Jun 05 '20 at 17:32
  • 1
    `df$Gain<-rep(c(1,3,5),each = 256*64);df$Ref<-rep(1:64, each = 256)` – Onyambu Jun 05 '20 at 17:34
  • @GregorThomas, thank you for the elegant solution! I think I can't mark a comment as an accepted solution, but if you answer the question I can? Thank you! – chrysrobyn Jun 05 '20 at 17:35
  • @Onyambu that c(1,3,5) is more elegant that what I had written, thank you! – chrysrobyn Jun 05 '20 at 17:36
  • 1
    If you look at `?rep`, there is an `each` argument and a `times` argument, with `times` used if you don't specify. Compare `rep(1:3, times = 3)` to `rep(1:3, each = 3)`. The `times` is vectorized too, so you can also do `rep(1:3, times = 2:4)`. – Gregor Thomas Jun 05 '20 at 17:36

0 Answers0