在 R 中创建没有循环或递归的特定向量 [英] Creation of a specific vector without loop or recursion in R
问题描述
我有第一个向量,假设 x 只包含 1 和 -1.然后,我有第二个向量 y,它由 1、-1 和零组成.现在,如果 x[i]
等于 1 并且 n 前导元素 (y[(in):i])
...
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 vector z that contains in index i a 1 if x[i]
equals 1 and a 1 exists within the vector y between the n precedent elements (y[(i-n):i])
...
更正式的:z <- ifelse(x == 1 && 1 %in% y[(index(y)-n):index(y)],1,0)代码>
我希望在 R 中创建这样一个向量而无需循环或递归.上面的命题不起作用,因为它不能识别以一个元素一个元素地使用表达式 y[(index(y)-n):index(y)]
.
I'm looking to create such a vector in R without looping or recursion. The proposition above does not work since it does not recognize to take the expression y[(index(y)-n):index(y)]
element by element.
非常感谢您的支持
推荐答案
这里有一种方法,它使用 cumsum
函数来测试到目前为止已经看到的数量.如果i
位置的1个数大于i-n
位置的1个数,则满足右边的条件.
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
这篇关于在 R 中创建没有循环或递归的特定向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!