[英]Transforming a numeric vector into list of intervals
I have the following vector 我有以下矢量
x <- c(1,3,4,5,8,9,10,13)
I wish to transform it into a set of intervals: 我希望将其转换为一组间隔:
iwant <- list(1, c(3,5), c(8,10), 13)
iwant
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 3 5
#>
#> [[3]]
#> [1] 8 10
#>
#> [[4]]
#> [1] 13
is there an easy way to tranform x
such into groups of interval ranges in R or with Rcpp (real x
vector may be have up to ~ 80M values) that I've completely missed? 是否有一种简单的方法可以将x
转换成R中的区间范围组或Rcpp(实际x
向量可能有多达~80M值)我完全错过了? If not can someone point me to an algorithm I can't seem to figure it out. 如果没有,有人可以指出我的算法,我似乎无法搞清楚。
It is not clear waht you are looking to do ,but here how you can reproduce the expected result: 目前尚不清楚你想要做什么,但在这里你如何重现预期的结果:
lapply(split(x,c(0,cumsum(diff(x)!=1))),
function(y)if(length(y)>2) c(y[1],tail(y,1))else y)
$`0`
[1] 1
$`1`
[1] 3 5
$`2`
[1] 8 10
$`3`
[1] 13
I'm not exactly sure how you're defining an instance of an interval but here's one way using the IRanges package ( installation instructions ). 我不确定你是如何定义一个间隔的实例,但这是使用IRanges包的一种方式( 安装说明 )。 It has really good documentation. 它有很好的文档。
require(IRanges)
reduce(IRanges(x, x))
# IRanges of length 4
# start end width
# [1] 1 1 1
# [2] 3 5 3
# [3] 8 10 3
# [4] 13 13 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.