我有一个包含多列信息的数据框,例如:
df <- data.frame(chr=c("chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr2", "chr2"), Gene=c("Happy", "Happy", "Happy", "Happy", "Happy", "Happy", "Happy", "Happy", "Sad", "Sad"), site = c(100, 120, 130, 300, 2000, 2300, 2342, 2451, 120, 123), value=c(20, 25, 21, 30, -80, 31, -79, -90, 10, 13))
> df
chr Gene site value
1 chr1 Happy 100 20
2 chr1 Happy 120 25
3 chr1 Happy 130 21
4 chr1 Happy 300 30
5 chr1 Happy 2000 -80
6 chr1 Happy 2300 31
7 chr1 Happy 2342 -79
8 chr1 Happy 2451 -90
9 chr2 Sad 120 10
10 chr2 Sad 123 13
我想创建一个汇总数据框,计算每个基因有多少聚集区域。我认为一个集群有任意数量的行,其中站点编号的差异不大于 1,000(我的数据按 chr 和站点排序)。首先,我创建了一个新列来计算连续行中站点之间的距离:
df$Distance <- c(1001, diff(df$site, lag=1, differences=1))
> df
chr Gene site value Distance
1 chr1 Happy 100 20 1001
2 chr1 Happy 120 25 20
3 chr1 Happy 130 21 10
4 chr1 Happy 300 30 170
5 chr1 Happy 2000 -80 1700
6 chr1 Happy 2300 31 300
7 chr1 Happy 2342 -79 42
8 chr1 Happy 2451 -90 109
9 chr2 Sad 120 10 -2331
10 chr2 Sad 123 13 3
我想为每个基因创建一个汇总表,其中汇总了在每个基因中发现的平均值为正或负的簇的数量。在上面的示例中,表格如下所示:
Gene PositiveClusters NegativeClusters
1 Happy 1 1
2 Sad 1 0