我很难想出以下问题的快速解决方案:
我有一组观测值的向量,它表示某些现象的观测时间。
example <- c(0,0,0,1,0,1,1,0,0,0,-1,0,0,-1,-1,0,0,1,0,0);
现在我想要消除特定观测之间的零值,假设某个现象会持续到出现矛盾的观测为止,例如,在第三次观测中观察到“1”,则在观测到第一个“-1”元素时,我只想保留“1”直到第11个元素。因此,我期望的输出如下:desired.output <- c(0,0,0,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,1,1,1);
> print(cbind(example, desired.output))
example desired.output
[1,] 0 0
[2,] 0 0
[3,] 0 0
[4,] 1 1
[5,] 0 1
[6,] 1 1
[7,] 1 1
[8,] 0 1
[9,] 0 1
[10,] 0 1
[11,] -1 -1
[12,] 0 -1
[13,] 0 -1
[14,] -1 -1
[15,] -1 -1
[16,] 0 -1
[17,] 0 -1
[18,] 1 1
[19,] 0 1
[20,] 0 1
我的笨拙解决方案是
for (i in 1:length(example)){
if (example[i] != 0){
current <- example[i];
while ((example[i] != -current) & (i <= length(example))){
example[i] <- current;
i <- i+1;
}
}
}
我将感激任何加速此过程的帮助。
L
和1L
:-) - Carl WitthoftfindInterval
的“UPD”比“UPD2”根据microbenchmark
测试快约4%。 - Carl Witthoft