首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除R中区间中的相交区域

删除R中区间中的相交区域
EN

Stack Overflow用户
提问于 2018-06-21 15:54:33
回答 1查看 54关注 0票数 0

如果我有间隔,我如何找到并删除R中的交叉点。例如,如果我有:

代码语言:javascript
复制
start=c(5,9,1,2,14,18); end=c(10,12,3,4,16,20)
d<-cbind(start, end)
start end
 5  10
 9  12
 1   3
 2   4
14  16
18  20

我希望输出是

代码语言:javascript
复制
start end
 5   8
11  12
 1   1
 4   4
14  16
18  20

例如,第一个区间与第二个区间相交,如果删除交点,则第一个区间变为(5,8)和第二个(11,12),因为9和10都包含在这两个区间中,因此应该删除它们。也就是说,如果存在交叉点,则测试区间,删除交叉点,并返回具有新起点和终点的区间。我想知道如何用R编写代码。

EN

回答 1

Stack Overflow用户

发布于 2018-06-21 21:13:35

这可能是您正在寻找的内容:

代码语言:javascript
复制
start <- c(5, 9, 1, 2, 14, 18)
end <- c(10, 12, 3, 4, 16, 20)
d <- cbind(start, end)

# create temporary data frame
temp <- d

# i loops among 1, 2 and 3, because 3 is half the length of vector start
for(i in seq(length(start) / 2)) {
  # both thisLine and nextLine will consider a pair of lines in the data frame
  # thisLine loops among 1, 3 and 5
  thisLine <- (2 * i) - 1
  # nextLine loops among 2, 4 and 6
  nextLine <- (2 * i)

  # if there is an intersection: meaning that start of nextLine is bigger than
  # the start of thisLine AND smaller than the end of thisline
  if((temp[nextLine,]["start"]) > temp[thisLine,]["start"] &
     (temp[nextLine,]["start"] < (temp[thisLine,]["end"]))) {
    # get initial end of thisLine
    initial_end_thisLine <- temp[thisLine,]["end"]
    # set new value for end of thisLine to be the start of nextLine - 1
    temp[thisLine,]["end"] <- temp[nextLine,]["start"] - 1
    # set new value for start of nextline to be the initial end of thisLine
    temp[nextLine,]["start"] <- initial_end_thisLine + 1
  }
}

# get the output
output <- temp

请注意:

1-在R中使用for循环并不是很好。我只是想写一个解决方案的例子。最好使用apply函数族。

2-我理解你的问题,你只需要比较每一对线并寻找交叉点。如果您还想将所有行相互比较,则需要另一种解决方案。

3-数据帧D被认为具有偶数行,以使该解决方案工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50963232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档