Creation of a specific vector without loop or recursion in R

后端 未结 2 1275
囚心锁ツ
囚心锁ツ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题