-1

I have a data frame with 8 columns and 177 rows. I need to loop this data frame over each day of the week so that each unique ID is repeated 7 times corresponding to the day of the week: Monday, Tuesday, etc.

I have tried searching for an answer to this, but have been unable to find one.

               [The image provides the first six rows of my current output. Columns v1, v2, and v3 all have unique values (v1 and v2 change in later rows) ][1]

I need it so that each row repeats seven times and corresponds to the day of the week.

  • Could you explain more? Maybe using a little example to illustrate the data frame you already have and the effect you want to achieve. – Consistency Nov 01 '17 at 15:33
  • Possible duplicate of [Replicate each row of data.frame and specify the number of replications for each row](https://stackoverflow.com/questions/2894775/replicate-each-row-of-data-frame-and-specify-the-number-of-replications-for-each) – Parfait Nov 01 '17 at 16:04
  • Thanks! Found a little more helpful function here: https://stackoverflow.com/questions/11121385/repeat-rows-of-a-data-frame. Solves the problem – mattnewbieR Nov 01 '17 at 16:25

1 Answers1

1

One possible solution is to use the CJ() function (cross join) from data.table:

df1 <- data.frame(id = 1:177, x1 = 1234L)

library(data.table)
setDT(df1)[CJ(id = id, weekday = 1:7), on = "id"]
       id   x1 weekday
   1:   1 1234       1
   2:   1 1234       2
   3:   1 1234       3
   4:   1 1234       4
   5:   1 1234       5
  ---                 
1235: 177 1234       3
1236: 177 1234       4
1237: 177 1234       5
1238: 177 1234       6
1239: 177 1234       7
Uwe
  • 41,420
  • 11
  • 90
  • 134