How do I create this following sequence?

Viewed 100

Use: seq(),rep()and possibly other commonly-used operators/functions,but NOT c()or any explicit loops to create the following sequences (compound expres-sions are allowed).

I have this sequence I wanted to create:

2.5 5.5 9.5 14.5 20.5 27.5 35.5

I know the increment is cumsum(3:8) but how do I put this into rep(seq(2.5, 35.5))? I tried:

rep(seq(2.5, 35.5, cumsum(3:8)))

but it gives me error. How do I do this? Thanks guys!

1 Answers

We need

c(2.5, 2.5 + cumsum(3:8))
[1]  2.5  5.5  9.5 14.5 20.5 27.5 35.5

or slightly more compact

2.5 + c(0, cumsum(3:8))
[1]  2.5  5.5  9.5 14.5 20.5 27.5 35.5

If we don't want any c, why not create a 0 vector and fill it

out <- numeric(7) 
# or use rep
out <- rep(0, 7)
out[1] <- 2.5
out[-1] <- 2.5 + cumsum(3:8)
out
[1]  2.5  5.5  9.5 14.5 20.5 27.5 35.5

Or use replace

replace(rep(2.5, 7), -1, 2.5 + cumsum(3:8))
[1]  2.5  5.5  9.5 14.5 20.5 27.5 35.5

Or as @user20650 mentioned

rep(2.5, 7) + unlist(list(0, cumsum(seq(3, 8))))
[1]  2.5  5.5  9.5 14.5 20.5 27.5 35.5

Or use lag

library(dplyr)
lag(2.5 + cumsum(3:9),  default = 2.5)
[1]  2.5  5.5  9.5 14.5 20.5 27.5 35.5
Related