我创建了一个基本上创建1000个二进制值的向量的函数。我已经能够使用rle
来计算连续1秒的最长连续数。如何在r中查找一个向量中的字符串?
我想知道如何在这个更大的向量中找到一个特定的向量(比如说c(1,0,0,1)
)?我希望它能够返回该向量的出现次数。所以c(1,0,0,1,1,0,0,1)
应该返回2,而c(1,0,0,0,1)
应该返回0
,我发现大多数解决方案只觉得是发生在所有的序列,并返回TRUE
或FALSE
,或者他们给了个人价值的结果,而不是特定的向量被指定。
这里是我到目前为止的代码:
# creates a function where a 1000 people choose either up or down.
updown <- function(){
n = 1000
X = rep(0,n)
Y = rbinom(n, 1, 1/2)
X[Y == 1] = "up"
X[Y == 0] = "down"
#calculate the length of the longest streak of ups:
Y1 <- rle(Y)
streaks <- Y1$lengths[Y1$values == c(1)]
max(streaks, na.rm=TRUE)
}
# repeat this process n times to find the average outcome.
longeststring <- replicate(1000, updown())
longeststring(p_vals)
@冯天其实我们需要使用前瞻断言,更新代码,让我知道如果它不起作用。 –
我明白了。你是对的。 –