Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modification of a Vector based on elements sequence

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.

like image 555
And_R Avatar asked Nov 27 '17 14:11

And_R


People also ask

Can vector elements be changed?

All the elements of a vector can be replaced by a specific element using java. util. Collections.

What create the series of number in sequence for a vector?

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.

Are elements ordered in a vector?

Yes; vector entries maintain a consistent position within the vector assuming you don't remove any items.


1 Answers

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
like image 67
talat Avatar answered Oct 12 '22 22:10

talat