Vectorizing loop over vector elements

后端 未结 3 2196
时光取名叫无心
时光取名叫无心 2021-02-20 01:12

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. <

3条回答
  •  抹茶落季
    2021-02-20 01:47

    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: It may be faster to calculate mch above with

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

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

提交回复
热议问题