How is it possible to transform the following vector:
x <- c(0, 0, 0, 1, 0, 3, 2, 0, 0, 0, 5, 0, 0, 0, 8)
into the desired form:
y <- c(1, 1, 1, 1, 3, 3, 2, 5, 5, 5, 5, 8, 8, 8, 8)
Any idea would be highly appreciated.
All the elements of a vector can be replaced by a specific element using java. util. Collections.
We can create a vector with a sequence of numbers by using − if the sequence of numbers needs to have only the difference of 1, otherwise seq function can be used.
Yes; vector entries maintain a consistent position within the vector assuming you don't remove any items.
Here's another approach using only base R:
idx <- x != 0
split(x, cumsum(idx) - idx) <- x[idx]
The x-vector is now:
x
#[1] 1 1 1 1 3 3 2 5 5 5 5 8 8 8 8
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