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

Create a numeric vector from 1 to n each time, given a vector of ns

It sounds confusing from the title, but it should be very clear with the following examples.

Say I have the following vector a:

a=c(3,10,6,7)

I want a vector b, so that it covers from 1 to each of the numbers in a each time, resulting in:

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

b=c(1,2,3,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,1,2,3,4,5,6,7)

To complete the task, if a number in a is ==1, I don’t want that 1 alone, but rather an NA. In this case, if a is:

a=c(3,10,6,1,7)

b should be:

b=c(1,2,3,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,NA,1,2,3,4,5,6,7)

How should I do that easily with base tools? Thanks!

>Solution :

Yes, sequence(a) should be preferred here over, e.g., unlist(lapply(a, seq_len)). And once you work out where the length-1 subsequences begin, you can subassign NA:

a <- c(3, 10, 6, 1, 7)
replace(sequence(a), cumsum(a)[a == 1], NA)
##  [1]  1  2  3  1  2  3  4  5  6  7
## [11]  8  9 10  1  2  3  4  5  6 NA
## [21]  1  2  3  4  5  6  7
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