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:
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!
CodePudding user response:
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