I would like to convert this piece of logic with purely matrix operations instead of for loops. The logic is that in my binary value vector, I want to note every transition point (i.e. where 0 turns to 1 and where 1 turns to 0). Otherwise I want to retain the original values. While a simple loop is fast enough for small vector, I’ll need to perform this operation several times over large datasets hence the need for efficiency via matrics.
x <- c(1,0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,0,1);
y <- rep(-2, length(x));
y[1] <- x[1];
for(i in 2:length(x)){
if((x[i]==1 && x[i-1]==0) || (x[i]==0 && x[i-1]==1)){
y[i] = -1;
}
else{
y[i] = x[i];
}
}
final value of y is
1 -1 0 0 0 -1 1 -1 0 -1 -1 -1 -1 -1 -1 0 0 -1
I’m a new convert to R, many thanks in advance
You can use
rlefor this: