Creation of a specific vector without loop or recursion in R

后端 未结 2 1257
囚心锁ツ
囚心锁ツ 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)
    
    0 讨论(0)
  • 2021-01-25 04:33

    Here's an approach that uses the cumsum function to test for the number of ones that have been seen so far. If the number of ones at position i is larger than the number of ones at position i-n, then the condition on the right will be satisfied.

    ## Generate some random y's.
    > y <- sample(-1:1, 25, replace=T)
    > y
     [1]  0  1 -1 -1 -1 -1 -1  1 -1 -1 -1 -1  0  0 -1 -1 -1  1 -1  1  1  0  0  0  1
    > n <- 3
    ## Compute number of ones seen at each position.
    > cs <- cumsum(ifelse(y == 1, 1, 0))
    > lagged.cs <- c(rep(0, n), cs[1:(length(cs)-n)])
    > (cs - lagged.cs) > 0
     [1] FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE
    [13] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
    [25]  TRUE
    
    0 讨论(0)
提交回复
热议问题