如何将带值的区间转换为R中的单个位置级别

如何将带值的区间转换为R中的单个位置级别,r,R,我有点纠结于以下问题: 我有表A(如下),我想通过计算间隔(表A中每个间隔的开始和结束)中重叠位置的总和(表A中的值)将其中定义的间隔合并/减少/转换为表B中的单个位置,如果有,或者如果没有重叠位置,则仅给出值,如果没有该位置的间隔,则为0。我更喜欢在R解决那个问题。我非常感谢你们的帮助 表A ID Start End Value 1 1 5 9 2 3 7 5 3 5 9 13 4 11 15 1 5 12 1

我有点纠结于以下问题:
我有表A(如下),我想通过计算间隔(表A中每个间隔的开始和结束)中重叠位置的总和(表A中的值)将其中定义的间隔合并/减少/转换为表B中的单个位置,如果有,或者如果没有重叠位置,则仅给出值,如果没有该位置的间隔,则为0。我更喜欢在R解决那个问题。我非常感谢你们的帮助

表A

ID Start End Value
1  1      5     9
2  3      7     5
3  5      9    13
4  11     15    1
5  12     16   18
6  14     18   21
转换为表B

Position Value
1        9
2        9
3        14
4        14
5        27
6        18
7        18
8        13
9        13
10       0
11       15
12       33
13       33
14       54
15       54
16       39
17       21
18       21

这不是一个非常直接的方法,但它可以完成工作:

df<-structure(list(ID = 1:6, Start = c(1L, 3L, 5L, 11L, 12L, 14L), 
                   End = c(5L, 7L, 9L, 15L, 16L, 18L), 
                   Value = c(9L, 5L, 13L, 1L, 18L, 21L)), .Names = c("ID", "Start", "End", "Value"),
              class = "data.frame", row.names = c(NA, 
                                                                                                                                                                -6L))
# create list matrix for each grouping
s1<-lapply(1:6, function(i) {matrix(c(df[i,2]:df[i,3], rep(df[i,4], (df[i,3]-df[i,2]+1))), nrow = (df[i,3]-df[i,2])+1)})
s2<-as.data.frame(do.call(rbind, s1))

#sum all of the like positions
library(dplyr)
wgaps<-summarise(group_by(s2, V1), sum(V2))

#create sequence with no gaps in it and match
nogaps<-data.frame(Position=seq(min(wgaps$V1), max(wgaps$V1)))
nogaps<-left_join(nogaps, wgaps, by=c("Position"= "V1"))
names(nogaps)<-c("Position", "value")   #rename
nogaps$value[is.na(nogaps$value)]<-0    #remove 0
d在一个类似(但不完全相同)的问题中,我使用Bioconductor的
IRanges
包找到了一个解决方案,请参阅。也许,
IRanges
中的
Rle
类可能是你的朋友。