如果我有间隔,我如何找到并删除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编写代码。
发布于 2018-06-21 21:13:35
这可能是您正在寻找的内容:
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被认为具有偶数行,以使该解决方案工作。
https://stackoverflow.com/questions/50963232
复制相似问题