向量化向量元素上的循环 [英] Vectorizing loop over vector elements

查看:61
本文介绍了向量化向量元素上的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很难为以下问题提供快速解决方案:

I find it hard to come up with a fast solution to the following problem:

我有一个观察向量,它指示观察某些现象的时间.

I have a vector of observations, which indicates the time of observation of certain phenomena.

example <- c(0,0,0,1,0,1,1,0,0,0,-1,0,0,-1,-1,0,0,1,0,0);

现在,我想消除特定观察值之间的零,因为假设某种现象一直持续到注意到矛盾的观察值为止,即 如果在第三次观察中观察到"1",那么当观察到第一个"-1"时,我只希望在第11个元素中只有"1".所以我想要的输出看起来像:

Now I would like to eliminate zeros between particular observations, given that a certain phenomenon is assumed to continue until a contradictory observation is noted, i.e., if ''1'' was observed in third observation, I would like to have only ''1'' up to 11th element, when first ''-1'' is observed. So my desired output looks like:

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

我la脚的解决方法是

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;
       }
    }
}

如果能帮助您加快速度,我将不胜感激.

I will appreciate any help with speeding this up.

推荐答案

我将尝试成为提供纯R解决方案的人:

I'll try to be the one to offer a pure R solution:

example <- c(0,0,0,1,0,1,1,0,0,0,-1,0,0,-1,-1,0,0,1,0,0);

cs = cumsum(example!=0);
mch = match(cs, cs);
desired.output = example[mch];

print(cbind(example,desired.output))

UPD:使用

计算上面的mch可能更快

UPD: It may be faster to calculate mch above with

mch = findInterval(cs-1,cs)+1

UPD2:我喜欢@Roland的回答.可以缩短为两行:

UPD2: I like the answer by @Roland. It can be shortened to two lines:

NN = (example != 0);
desired.output = c(example[1], example[NN])[cumsum(NN) + 1L];

这篇关于向量化向量元素上的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆