r-获取连续数字而不重复



从一个随机的数字序列{"1"、"2"、"3"、"4"、"5"}中,要求确定由3个连续数字组成的组出现的次数,这意味着,以基=c("1","2","3","4","5"(生成的次数,下列组{"123","234","345"}中的任何一个。

# I undertand that I have generate a sample with 5 numbers
a<-c(sample(1:5,5))
a
#I generated the list, as you can see I didn't fix a seed because I know that in every single sequence I will have differents grupos of 3 consecutive numbers, so I should obtain something like this
b<-c(2,3,4,5,1) #this example gives me just one that it would be {2,3,4}
b
#answer expected
1
#Then, I don't know how to obtain the sequence I have tried with permutations and combinations but I don't get it.

这将统计任何出现的三项连续增加(例如123(。

countsequence <- function(x){
if (length(x)<3){
return(0)
}
count <- 0
for(i in 3:length(x)){
if(x[i-1]==x[i]-1 && x[i-2] == x[i]-2){
count <- count + 1
}
}
return(count)
} 
countsequence(1:5)
countsequence(c(2, 3, 4, 1, 5))

参数k用于子序列长度(在您的情况下为3(:

f <- function(b, k = 3){
if(k > length(b)) return(0)

check_list <- lapply(k:length(b), function(x) all(diff(b[(x-k+1):x]) == 1)) 
sum(unlist(check_list))
}

如果要计算递增或递减子序列,请使用适当的关系和数字替换==1

最新更新