Reputation: 183
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
Upvotes: 6
Views: 600
Reputation: 183
here's another way, using seq()
x<-1:20
start_<-4
step_<-5
myseq<-seq(start_,20,by=step_)
x[c(myseq,myseq+1)]<-0
x
# [1] 1 2 3 0 0 6 7 8 0 0 11 12 13 0 0 16 17 18 0 0
Upvotes: 1
Reputation: 887691
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
Upvotes: 4