我有两个数据框data
:
data <- structure(list(chrom = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 3L,
3L, 4L, 4L, 4L, 4L), pos = c(10L, 200L, 134L, 400L, 600L, 1000L,
20L, 33L, 40L, 45L, 50L, 55L, 100L, 123L)), .Names = c("chrom",
"pos"), class = "data.frame", row.names = c(NA, -14L))
并且tss_locations
:
tss_locations <- structure(list(gene = structure(c(1L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 2L, 3L), .Label = c("gene1", "gene10", "gene11", "gene2",
"gene3", "gene4", "gene5", "gene6", "gene7", "gene8", "gene9"
), class = "factor"), chrom = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L, 4L, 4L), tss = c(5L, 10L, 23L, 1340L, 313L, 88L, 44L, 57L,
88L, 74L, 127L)), .Names = c("gene", "chrom", "tss"), class = "data.frame", row.names = c(NA,
-11L))
和一个功能找到的位置之间最接近的匹配data
(pos
)和位置tss_locations
(tss
)。我想作比较,只有在chrom
价值上是相同的pos
和tss
。
到目前为止,我通过首先过滤两个数据帧以选择相同的 chrom,然后通过我的函数运行它们来实现这一点:
# Filter both data frames on same chrom
data<-filter(data, chrom == 1)
tss_locations<-filter(tss_locations, chrom == 1)
# apply fun2
dist2tss<-lapply(data$pos, fun2)
fun2 <- function(p) {
# Get index of nearest tss
index<-which.min(abs(tss_locations$tss - p))
# Get corresponding tss, chrom and gene
closestTss<-tss_locations$tss[index]
chrom<-as.character(tss_locations$chrom[index])
gene<-as.character(tss_locations$gene[index])
# Calculate distance
dist<-(p-closestTss)
list(p, closestTss, dist, chrom, gene)
}
# Convert to data frame
dist2tss<-do.call(rbind, dist2tss)
dist2tss<-as.data.frame(dist2tss)
colnames(dist2tss)=c("snp", "closest_tss", "min_dist", "chrom", "closest_gene")
dist2tss$min_dist<-as.numeric(dist2tss$min_dist)
我试过把它放在一个 for 循环中,即:
for (c in levels(data$chrom)){
data<-filter(data, chrom == c)
tss_locations<-filter(tss_locations, chrom == c)
...
}
但我不知道如何让它为每个染色体返回一个数据框,然后将它们合并在一起,以便我可以绘制全局距离。
任何帮助表示赞赏
一个玩具示例,但在循环中构建一个列表并在最后执行 do.call(假设它们都具有相同的列结构?)
df1 <- data.frame(cell=c(1,2,3),val=c(345,123,466))
df2 <- data.frame(cell=c(67,3,2),val=c(234,234,56))
df3 <- data.frame(cell=c(3,67,23),val=c(23,8,34))
l <- list()
for(i in 1:3){
df.now <- get(paste0("df",i))
l[[i]] <- df.now
}
do.call(rbind,l)
在您的上下文中,您可以像在初始工作流程中一样为每个染色体构建数据框,并在循环结束时使用该新数据框填充列表元素。然后完全调用它们,如下所示:
l <- list()
for (c in levels(data$chrom)){
data<-filter(data, chrom == c)
tss_locations<-filter(tss_locations, chrom == c)
dist2tss<-lapply(df$pos, fun2)
dist2tss<-do.call(rbind, dist2tss)
dist2tss<-as.data.frame(dist2tss)
colnames(dist2tss)=c("snp", "closest_tss", "min_dist", "chrom", "closest_gene")
dist2tss$min_dist<-as.numeric(dist2tss$min_dist)
l[[c]] <- dist2tss
}
dist2tss<-do.call(rbind,l)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句