R fill vector efficiently

后端 未结 4 647
不思量自难忘°
不思量自难忘° 2021-01-22 20:22

I have a fairly big vector (>500,000 in length). It contains a bunch of NA interspersed with 1 and it is always guaranteed that it begins with 1<

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-22 20:26

    A vectorised solution would look like:

    v1[-1] <- ifelse(diff(v2), 0, v1[-length(v1)])
    

    But the above won't work, and I don't think you can avoid an explicit loop since, if I understand correctly, you want to propagate new values. So, how about:

    cmp <- diff(v2)
    for (i in 2:length(v1)){
        v1[i] <- if(cmp[i-1]) 0 else v1[i-1]
    }
    

提交回复
热议问题