I am trying to replace values of a vector of sequence 1 to 100, such that after every 3 elements, the next 2 are replaced by 0s. for example:
a<-1:20
I want it to be like this:
a <- c(1, 2, 3, 0, 0, 6, 7, 8, 0, 0, 11, 12, 13, 0, 0, 16, 17, 18, 0, 0)
is there a way to do this automatically?
thanks for any help
The replacement of values in a vector with the values in the same vector can be done with the help of replace function. The replace function will use the index of the value that needs to be replaced and the index of the value that needs to be placed but the output will be the value in the vector.
A very efficient way to create equally-spaced numeric vectors is to use the seq() function, which is short for sequence. To use the seq() function, you can specify the start value of the sequence in the from argument, the limit end value in the to argument, and the increment in the by argument.
We can use rep
with a recycling logical vector to assign values in certain positions to 0
a[rep(c(FALSE, TRUE), c(3,2))] <- 0
a
#[1] 1 2 3 0 0 6 7 8 0 0 11 12 13 0 0 16 17 18 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With