Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace vector values in a sequence at regular intervals in R?

Tags:

r

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

like image 439
M Terry Avatar asked Feb 15 '17 12:02

M Terry


People also ask

How do you replace all values in a vector?

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.

How do you create an equally spaced vector in R?

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.


1 Answers

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
like image 135
akrun Avatar answered Oct 23 '22 05:10

akrun