Creation of a specific vector without loop or recursion in R

后端 未结 2 1251
囚心锁ツ
囚心锁ツ 2021-01-25 03:42

I\'ve got a first vector, let\'s say x that consists only of 1\'s and -1\'s. Then, I have a second vector y that consists of 1\'s, -1\'s, and zeros. Now, I\'d like to create a v

2条回答
  •  有刺的猬
    2021-01-25 04:31

    You could use apply like this, although it is essentially a pretty way to do a loop, I'm not sure if it will be faster (it may or may not).

    y1 <- unlist(lapply(1:length(x), function(i){1 %in% y[max(0, (i-n)):i]}))
    z <- as.numeric(x==1) * as.numeric(y1)
    

提交回复
热议问题