选择一组间隔(范围)之内/之外的值R [英] Select values within/outside of a set of intervals (ranges) R

查看:68
本文介绍了选择一组间隔(范围)之内/之外的值R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有某种索引,例如:

index <- 1:100

我也有排除间隔"/范围的列表

I've also got a list of "exclusion intervals" / ranges

exclude <- data.frame(start = c(5,50, 90), end = c(10,55, 95))

  start end
1     5  10
2    50  55
3    90  95

我正在寻找一种有效的方法(在R中),以删除属于 exclude 数据框范围内的所有索引

I'm looking for an efficient way (in R) to remove all the indexes that belong in the ranges in the exclude data frame

因此所需的输出将是:

1,2,3,4,  11,12,...,48,49,  56,57,...,88,89,  96,97,98,99,100

我可以迭代地执行此操作:遍历每个排除间隔(使用 ddply )并迭代地删除每个间隔中的索引.但是,有没有更有效的方法(或功能)呢?

I could do this iteratively: go over every exclusion interval (using ddply) and iteratively remove indexes that fall in each interval. But is there a more efficient way (or function) that does this?

我正在使用 library(intervals)来计算我的间隔,我找不到内置函数来执行此操作.

I'm using library(intervals) to calculate my intervals, I could not find a built-in function tha does this.

推荐答案

我们可以使用 Map 来获取'start''end'列中的相应元素的顺序, unlist 创建一个 vector ,并使用 setdiff 获取不在 vector 中的'index'值.

We can use Map to get the sequence for the corresponding elements in 'start' 'end' columns, unlist to create a vector and use setdiff to get the values of 'index' that are not in the vector.

setdiff(index,unlist(with(exclude, Map(`:`, start, end))))
#[1]   1   2   3   4  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25
#[20]  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44
#[39]  45  46  47  48  49  56  57  58  59  60  61  62  63  64  65  66  67  68  69
#[58]  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88
#[77]  89  96  97  98  99 100


或者我们可以使用 rep ,然后使用 setdiff .

i1 <- with(exclude, end-start) +1L
setdiff(index,with(exclude, rep(start, i1)+ sequence(i1)-1))

注意:两种方法都返回需要排除的索引位置.在上述情况下,原始向量(索引")是一个序列,因此我使用了 setdiff .如果它包含随机元素,请适当使用位置矢量,即

NOTE: Both the methods return the index position that needs to be excluded. In the above case, the original vector ('index') is a sequence so I used setdiff. If it contains random elements, use the position vector appropriately, i.e.

index[-unlist(with(exclude, Map(`:`, start, end)))]

index[setdiff(seq_along(index), unlist(with(exclude, 
                       Map(`:`, start, end))))]

这篇关于选择一组间隔(范围)之内/之外的值R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆