将来自不同行数的表与主MAP表组合在一起

时间:2015-11-20 13:17:10

标签: r join merge data.table genome

该数据集代表基因组图谱位置(chr和start),每个位置的序列覆盖度(深度)总和为20个人(dat)

示例:

gbsgre <- "chr start end depth
chr1 3273 3273 7
chr1 3274 3274 3
chr1 3275 3275 8
chr1 3276 3276 4
chr1 3277 3277 25"
gbsgre <- read.table(text=gbsgre, header=T)

该数据集代表每个位置的个体覆盖率(V3)的基因组图谱位置(V1加V2)。

示例:

df1 <- "chr start depth
        chr1 3273 4
        chr1 3276 4
        chr1 3277 15"
df1 <- read.table(text=df1, header=T)

df2 <- "chr start depth
        chr1 3273 3
        chr1 3274 3
        chr1 3275 8
        chr1 3277 10"

df2 <- read.table(text=df2, header=T)

dat <- NULL

dat[[1]] <- df1
dat[[2]] <- df2

> dat
[[1]]
   chr start depth
1 chr1  3273     4
2 chr1  3276     4
3 chr1  3277    15

[[2]]
   chr start depth
1 chr1  3273     3
2 chr1  3274     3
3 chr1  3275     8
4 chr1  3277    10

根据chr上的startgbsgre位置,我需要跨越每20只动物的所有20个深度(V3)([[1]]到[[20] ]])到主表(gbsgre)生成最终表,如下所示: 第一列将是染色体位置(V1),第二列(V2)将是起始位置,第三列将是“gbsgre”数据集的深度(V3),第四列(V4)将是深度(dat /来自“dat”的[[1]]的V3),依此类推,直到第24列,这将是“dat”数据集上[[20]]的深度。 但是一个非常重要的事情是,20个人的缺失数据应该被认为是零(“0”)。 最终表的数量应该与“gbsgre”相同。

#Example Result
> GBSMeDIP
chr start   depth   depth1  depth2
1: chr1 3273    7   4   3
2: chr1 3274    3   0   3 
3: chr1 3275    8   0   8 
4: chr1 3276    4   4   0 
5: chr1 3277    25  15  10

2 个答案:

答案 0 :(得分:2)

使用data.table

# set names to your list `dat` first
setattr(dat, 'names', paste0("depth", seq_along(dat)))
# bind them by rows and reshape to wide form
dcast(rbindlist(dat, idcol="id"), chr + start ~ id, fill=0L)
#     chr start depth1 depth2
# 1: chr1  3273      4      3
# 2: chr1  3274      0      3
# 3: chr1  3275      0      8
# 4: chr1  3276      4      0
# 5: chr1  3277     15     10

答案 1 :(得分:0)

这应该可以解决问题:

 for(k in 1:length(dat)){
  datx <- dat[[k]]
  datx$tag <- paste0(datx$chr, "-", datx$start)
  if(k==1){
  datall <- datx
  colnames(datall)[3] <- paste0("depth", k)
  }
  if(k>1){
    colnames(datx)[3] <- paste0("depth", k)
    datx <- datx[, -c(1:2)]
    datall <- merge(datall, datx, by="tag", all.y=TRUE, all.x=TRUE) 
  }
}
library(stringr)
nam <- str_split_fixed(datall$tag, "-", 2)
datall <- cbind(nam, datall) 
datall <- datall[, -c(3:5)]
colnames(datall)[1:2] <- c("chr", "start")
datall[is.na(datall)] <- 0

这给了你:

   > datall
   chr start depth1 depth2
1 chr1  3273      4      3
2 chr1  3274      0      3
3 chr1  3275      0      8
4 chr1  3276      4      0
5 chr1  3277     15     10