【问题标题】:how to get min number and max number in a set of non continuous number in R如何在R中的一组非连续数字中获取最小数字和最大数字
【发布时间】:2016-02-25 18:50:39
【问题描述】:

我有一组数字:1,2,3,7,8,9,12,13,14...,我想得到每个连续部分的最小值和最大值,所以结果应该是 1-3,7-9,12-14

我可以使用 for 循环来比较并获得最小值最大值,但如果我有超过 1000 万个数字,这种方式会花费我很长时间......

有人知道是否有更快的方法来获得我想要的东西吗? 谢谢!

【问题讨论】:

  • 你试过什么,你在哪里卡住了?你可以试试diff

标签: r numeric minmax


【解决方案1】:

如 cmets 中所述,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

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2013-11-09
    相关资源
    最近更新 更多