如何在R中的一组非连续数中获得最小数和最大数
how to get min number and max number in a set of non continuous number in R
我有一组数字:1,2,3,7,8,9,12,13,14...
,我想得到每个连续部分的最小值和最大值,所以结果应该是 1-3,7-9,12-14
。
我可以使用 for 循环来比较并获得最小最大值,但是如果我有超过 1000 万个数字,这种方法会花费我很长时间...
有人知道是否有更快的方法来获得我想要的东西吗?
谢谢!
如评论中所述,diff
可以帮助找出差距。使用该索引,我们可以拆分向量并提取每组的第一个和最后一个:
c(sapply(split(x, cumsum(c(T, diff(x)>1))), function(v) c(v[1], tail(v,1)*-1)))
[1] 1 -3 7 -9 12 -14
解决方案已解决。为了扩展,我们可以将每个调用分开:
#Identify gaps in vector
changes <- cumsum(c(TRUE, diff(x) > 1L)
#Split vector on the above index
veclist <- split(x, changes)
#function to extract first item and the last item multiplied by -1
first_last <- function(v) c(v[1], tail(v,1)*-1)
#extract first and last from veclist
mat <- sapply(veclist, first_last)
#Remove list structure
c(mat)
[1] 1 -3 7 -9 12 -14
我有一组数字:1,2,3,7,8,9,12,13,14...
,我想得到每个连续部分的最小值和最大值,所以结果应该是 1-3,7-9,12-14
。
我可以使用 for 循环来比较并获得最小最大值,但是如果我有超过 1000 万个数字,这种方法会花费我很长时间...
有人知道是否有更快的方法来获得我想要的东西吗? 谢谢!
如评论中所述,diff
可以帮助找出差距。使用该索引,我们可以拆分向量并提取每组的第一个和最后一个:
c(sapply(split(x, cumsum(c(T, diff(x)>1))), function(v) c(v[1], tail(v,1)*-1)))
[1] 1 -3 7 -9 12 -14
解决方案已解决。为了扩展,我们可以将每个调用分开:
#Identify gaps in vector
changes <- cumsum(c(TRUE, diff(x) > 1L)
#Split vector on the above index
veclist <- split(x, changes)
#function to extract first item and the last item multiplied by -1
first_last <- function(v) c(v[1], tail(v,1)*-1)
#extract first and last from veclist
mat <- sapply(veclist, first_last)
#Remove list structure
c(mat)
[1] 1 -3 7 -9 12 -14