确定R中的向量中是否有x个连续重复项
我有以下向量:确定R中的向量中是否有x个连续重复项,r,R,我有以下向量: p<-c(0,0,1,1,1,3,2,3,2,2,2,2) 我可以做一个for循环来计算向量中TRUE的数量,但问题是连续计数器将关闭1。你们能想出其他的解决办法吗?p你们也可以 p<-c(0,0,1,1,1,3,2,3,2,2,2,2) find.dup <- function(x, n) { consec <- 1 for(i in 2:length(x)) { if(x[i] == x[i-1]) { consec &
p<-c(0,0,1,1,1,3,2,3,2,2,2,2)
我可以做一个for循环来计算向量中TRUE的数量,但问题是连续计数器将关闭1。你们能想出其他的解决办法吗?p你们也可以
p<-c(0,0,1,1,1,3,2,3,2,2,2,2)
find.dup <- function(x, n) {
consec <- 1
for(i in 2:length(x)) {
if(x[i] == x[i-1]) {
consec <- consec + 1
} else {
consec <- 1
}
if(consec == n)
return(TRUE) # or you could return x[i]
}
return(FALSE)
}
find.dup(p,3)
# [1] TRUE
find.dup(p,4)
# [1] TRUE
find.dup(p,5)
# [1] FALSE
find.dup <- function(x, n){
n %in% rle(x)$lengths
}
find.dup(p,3)
#[1] TRUE
find.dup(p,2)
#[1] TRUE
find.dup(p,5)
#[1] FALSE
find.dup(p,4)
#[1] TRUE
find.dup-Ha!我知道有一个包裹在做这个,我记不起是哪一个了。你就是那个男人@DominicComtoisrle
是一个base R
函数。无论何时,只要出现任何与连续
数字相关的内容,它都非常有用。ooops right,而不是package。我知道,过去也用过。但是我的记忆不能容纳所有语言的所有函数:D
find.dup <- function(x, n){
n %in% rle(x)$lengths
}
find.dup(p,3)
#[1] TRUE
find.dup(p,2)
#[1] TRUE
find.dup(p,5)
#[1] FALSE
find.dup(p,4)
#[1] TRUE