My data structure is as follows:
| rad_1 | division_num | interval |
|---|---|---|
| 1 | 2 | 4 |
| 1 | 3 | 2 |
| 2 | 3 | 3 |
I want to expand the rows by division and interval. If the interval is 4 and the division is 2 then expand the row eight times as 4 x 2 is 8. Similarly, if the interval is 2 and the division is 3 then expand the row 6 times as 2 x 3 is 6.
Code I tried:
dt1[, row_index := 1:.N]
dt1 <- dt1[rep(seq_len(.N), dt1$division), ]
dt1[, new_row := seq_len(division) - 1 + interval * (row_index - 1), by = row_index]
Expected output:
| rad_1 | division_num | interval |
|---|---|---|
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 2 | 4 |
| 1 | 3 | 2 |
| 1 | 3 | 2 |
| 1 | 3 | 2 |
| 1 | 3 | 2 |
| 1 | 3 | 2 |
| 1 | 3 | 2 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
| 2 | 3 | 3 |
You could use
tidyr::uncount