繁体   English   中英

在R中以间隔删除相交区域

[英]Removed intersection regions in intervals in R

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

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

我希望输出是

start end
 5   8
11  12
 1   1
 4   4
14  16
18  20

例如,第一个间隔与第二个间隔相交,然后,如果删除交集,则第一个间隔变为(5,8),第二个间隔变为(11,12),因为两个间隔中都包含9和10,因此应将其删除。 即测试区间,如果有任何交集,则删除交集,并以新的起点和终点返回区间。 我想知道如何在R中编写代码。

这可能是您要寻找的:

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应该具有偶数行,此解决方案才能起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM