I am trying to replace all the groups of elements in a vector that sum up to zero with NAs. The size of each group is 3. For instance:
a = c(0,0,0,0,2,3,1,0,2,0,0,0,0,1,2,0,0,0)
should be finally:
c(NA,NA,NA,0,2,3,1,0,2,NA,NA,NA,0,1,2,NA,NA,NA)
Until now, I have managed to find the groups having the sum equal to zero via:
b = which(tapply(a,rep(1:(length(a)/3),each=3),sum) == 0)
which yields c(1,4,6)
I then calculate the starting indexes of the groups in the vector via: b <- b*3-2
.
Probably there is a more elegant way, but this is what I've stitched together so far.
Now I am stuck at "expanding" the vector of start indexes, to generate a sequence of the elements to be replaced. For instance, if vector b
now contains c(1,10,16)
, I will need a sequence c(1,2,3,10,11,12,16,17,18)
which are the indexes of the elements to replace by NAs.
If you have any idea of a solution without a for
loop or even a more simple/elegant solution for the whole problem, I would appreciate it. Thank you.
Marius