Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Repeat each value in vector x times where x = next value – prev value

I have a vector that looks like

x <- c(1, 4, 7, 9)

I need output as (1,1,1,4,4,4,7,7,9). Repeat 1 three times that is (4-1), repeat 4 three times (7-4) and so on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x <- c(1, 4, 7, 9)

I have no idea what to do next. I dont want a for loop for this. I know rep() can be used for repeat. But how many times need to be determined from vector itself.

>Solution :

rep(x, c(diff(x), 1))
[1] 1 1 1 4 4 4 7 7 9

cummax(`[<-`(logical(max(x)),x,x))
[1] 1 1 1 4 4 4 7 7 9
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading