我正在R中进行一些分析,但是我需要计算连续的重复次数,并把ID放在一起。如果有相似的ID,我不想汇总,而当连续重复时,我想聚合特定的ID。我有一个包含这些条目的文件。
Probe Set ID Call Codes Chromosomal Position
SNP_A-2131660 BB 1156131
SNP_A-1967418 AB 2234251
SNP_A-1969580 BB 2329564
SNP_A-4263484 BB 2553624
SNP_A-1978185 AA 2936870
SNP_A-4264431 AA 2951834
SNP_A-1980898 BB 3095126
SNP_A-1983139 AA 3165267
SNP_A-4265735 AA 3302871
SNP_A-1995832 AA 3705226
SNP_A-1995893 AA 3720965
SNP_A-1997689 BB 3763164
SNP_A-1997709 AA 3763567
SNP_A-1997896 AA 3766240
SNP_A-1997922 AA 3766286
SNP_A-2000230 AA 4340877
SNP_A-2000332 AB 4343434
我想计算连续值(即BB,AB,(BB,BB)),如果还有其他两列的总和。
我尝试了不同的方法,但是我只能使用R中的此代码来执行连续重复计数。
# I got the counts
dfAA <- as.data.frame(with(rle(myfile$Call.Codes), lengths[values == "AA"]))
# I got the counts and the counted values
dfAA_02<-as.data.frame(rev(unclass(rle(myfile$Call.Codes))))
我不知道如何执行第二部分。
那就是我最后想要获得的。
Counts Aggregation_probeset_ID Aggregation Chromosomal position
BB 1 SNP_A-2131660 1156131
AB 1 SNP_A-1967418 2234251
BB 2 SNP_A-1969580, SNP_A-4263484 2329564, 2553624
AA 2 SNP_A-1978185, SNP_A-4264431 2936870, 2951834
AA 4 SNP_A-1983139, SNP_A-4265735, SNP_A-1995832, SNP_A-1995893 3165267, 3302871, 3705226, 3720965
这是您要找的东西吗?
library(data.table)
library(dplyr)
data[, lag := shift(Call_Codes, 1L, fill = , type = "lag")]
data[, new_group := if_else(lag != Call_Codes, 1, 0, missing = 1)]
data[, new_group := cumsum(new_group)]
data[, .(counts = .N,
Aggregation_probeset_ID = paste(Probe_Set_ID , collapse=","),
Aggregation_Chromosomal_position = paste(Chromosomal_Position , collapse=","))
, .(Call_Codes, new_group)][, -c('new_group')]
结果:
Call_Codes counts Aggregation_probeset_ID Aggregation_Chromosomal_position
1: BB 1 SNP_A-2131660 1156131
2: AB 1 SNP_A-1967418 2234251
3: BB 2 SNP_A-1969580,SNP_A-4263484 2329564,2553624
4: AA 2 SNP_A-1978185,SNP_A-4264431 2936870,2951834
5: BB 1 SNP_A-1980898 3095126
6: AA 4 SNP_A-1983139,SNP_A-4265735,SNP_A-1995832,SNP_A-1995893 3165267,3302871,3705226,3720965
7: BB 1 SNP_A-1997689 3763164
8: AA 4 SNP_A-1997709,SNP_A-1997896,SNP_A-1997922,SNP_A-2000230 3763567,3766240,3766286,4340877
9: AB 1 SNP_A-2000332 4343434
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句