-1

I have the following input data frame with 4 columns and 3 rows. The time column can take value from 1 to the corresponding value of the maturity column for that customer, I want to create more observations for each customer till the value of time is = value of maturity, with the other columns retaining their original value. Please see the below links for input and expected output

Input

Input

Output

Output

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • 1
    Images are not a good way of posting data (or code). [Relevant xkcd](https://xkcd.com/2116/). Can you post sample data in `dput` format? Please edit **the question** with the code you've tried and with the output of `dput(df)`. – Rui Barradas Sep 09 '20 at 17:24

2 Answers2

0

Here is a dplyr solution inspired but not exactly equal to this post.

library(dplyr)

df <- data.frame(custno = 1:3, time = 1, dept = c("A", "B", "A"))

df %>% 
  slice(rep(1:n(), each = 5)) %>%
  group_by(custno) %>%
  mutate(time = seq_along(time))

Edit

After the comments by the OP, the following seems to be better.

First, the data:

df <- data.frame(custno = 1:3, time = 1, 
                 dept = c("A", "B", "A"),
                 maturity = c(5,4,6))

And the solution.

df %>% 
  tidyr::uncount(maturity) %>%
  group_by(custno) %>%
  mutate(time = seq_along(time))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

We can also use slice with row_number

library(dplyr)
library(data.table)
df %>% 
    slice(rep(row_number(), maturity)) %>%
    mutate(time = rowid(custno))

data

df <- data.frame(custno = 1:3, time = 1, 
                 dept = c("A", "B", "A"),
                 maturity = c(5,4,6))
akrun
  • 874,273
  • 37
  • 540
  • 662