Home > Net >  Generate specified increment steps but fill in the previous values in between each step?
Generate specified increment steps but fill in the previous values in between each step?

Time:08-21

I supposed I want to generate a vector with incremental steps like so:

> seq(1, 20, by=5)
[1]  1  6 11 16

however what I really want is to return a vector that is filled with the previous value up to the next step?

1,1,1,1,1,6,6,6,6,6,11,11,11,11,11,16

can this be done with without some convoluted looping? thanks in advance.

CodePudding user response:

We could use length.out

rep(seq(1, 20, by = 5), each = 5, length.out = 16)
[1]  1  1  1  1  1  6  6  6  6  6 11 11 11 11 11 16

CodePudding user response:

Update: Request OP:

x <- seq(1, 20, by=5)
y <- c(rep(x[-length(x)], each=5), x[length(x)])

y[duplicated(y)] <- 0

 [1]  1  0  0  0  0  6  0  0  0  0 11  0  0  0  0 16

Here is an alternative approach: We use length to identify the last value in the vector. Subset first all values except the last and repeat each 5 times, as next step we put the last value again into the vector with c():

x <- seq(1, 20, by=5)
c(rep(x[-length(x)], each=5), x[length(x)])

 [1]  1  1  1  1  1  6  6  6  6  6 11 11 11 11 11 16

CodePudding user response:

  • We can use
x <- seq(1, 20, by=5)

rep(x , times = c(diff(x) , 1))

#> [1]  1  1  1  1  1  6  6  6  6  6 11 11 11 11 11 16
  • Related