Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
确定R中的数字序列何时中断_R - Fatal编程技术网

确定R中的数字序列何时中断

确定R中的数字序列何时中断,r,R,假设我有一系列数字: seq1<-c(1:20,25:40,48:60) 谢谢你的帮助 为了显示我惨败的尝试: nums<-min(seq1):max(seq1) %in% seq1 which(nums==F)[1] res.vec<-vector() counter<-0 res.vec2<-vector() counter2<-0 for (i in 2:length(seq1)){ if(nums[i]==F & nums[i-1]!

假设我有一系列数字:

seq1<-c(1:20,25:40,48:60)
谢谢你的帮助

为了显示我惨败的尝试:

nums<-min(seq1):max(seq1) %in% seq1
which(nums==F)[1]

res.vec<-vector()
counter<-0
res.vec2<-vector()
counter2<-0

for (i in 2:length(seq1)){
  if(nums[i]==F & nums[i-1]!=F){
    counter<-counter+1
    res.vec[counter]<-seq1[i]
  }

  if(nums[i]==T & nums[i-1]!=T){
    counter2<-counter2+1
    res.vec2[counter2]<-seq1[i]
  }


}

cbind(res.vec,res.vec2)

nums函数
diff
将为您提供连续值之间的差异

> x <- c(1,2,3,5,6,3)
> diff(x)
[1] 1 1 2 1 -3
>x差异(x)
[1] 1 1 2 1 -3
现在在序列中查找那些不等于“断点”的值

考虑到这里的评论。对于一般用途,您可以使用

fun<-function(data,threshold){
   t<-which(c(1,diff(data)) != threshold)
   return(t)
}

fun函数
diff
将为您提供连续值之间的差异

> x <- c(1,2,3,5,6,3)
> diff(x)
[1] 1 1 2 1 -3
>x差异(x)
[1] 1 1 2 1 -3
现在在序列中查找那些不等于“断点”的值

考虑到这里的评论。对于一般用途,您可以使用

fun<-function(data,threshold){
   t<-which(c(1,diff(data)) != threshold)
   return(t)
}

fun我对通用函数做了一些修改,因此我认为这应该是一个单独的答案

你可以试试

seq1<-c(1:20,25:40,48:60)

myfun<-function(data,threshold){
   cut<-which(c(1,diff(data))>threshold)
   return(cut)
}
为了更好地使用它,可以方便地创建一个对象

pru<-myfun(seq1,1)

我已经改变了一般功能一点,所以我认为这应该是一个单独的答案

你可以试试

seq1<-c(1:20,25:40,48:60)

myfun<-function(data,threshold){
   cut<-which(c(1,diff(data))>threshold)
   return(cut)
}
为了更好地使用它,可以方便地创建一个对象

pru<-myfun(seq1,1)

我知道OP没有要求它,但我认为将这种方法与diff一起构建到函数中会非常棒。也许类似于函数(序列、阈值)的东西可以识别序列中的阈值跳变。这仍然没有达到预期的输出。@Davidernburg你是对的,我已经为这个问题添加了我自己的答案now@DavidArenburg相当地然而,我认为这是解决问题的关键因素。我想读者可以从那里接受。我知道OP没有要求它,但我认为将这种方法与diff内置到函数中会很棒。也许类似于函数(序列、阈值)的东西可以识别序列中的阈值跳变。这仍然没有达到预期的输出。@Davidernburg你是对的,我已经为这个问题添加了我自己的答案now@DavidArenburg相当地然而,我认为这是解决问题的关键因素。我想读者可以从这里开始。你确定你想要21,24和41,47而不是21,25和37,48吗?你确定你想要21,24和41,47而不是21,25和37,48吗?