gpt4 book ai didi

R,在向量化的范围内加入

转载 作者:行者123 更新时间:2023-12-04 09:43:58 25 4
gpt4 key购买 nike

我正在尝试连接两个数据集,其中一个数据集中的变量(或基因组中的位置)适合第二个数据集中的范围(基因开始/停止位置)。然而,位置不是唯一的,而是嵌套在一个额外的列(染色体)中。基因起始/终止位置也是如此。我的目标是将每个位置与相应的注释和效果链接起来。

例如:

library(sqldf)
set.seed(100)
a <- data.frame(
annotation = sample(c("this", "that", "other"), 3, replace=TRUE),
start = seq(1, 30, 10),
chr = sample(1:3, 3, replace=TRUE)
)
a$stop <- a$start + 10
b <- data.frame(
chr = sample(1:3, 3, replace=TRUE),
position = sample(1:15, 3, replace=TRUE),
effect = sample(c("high", "low"), 3, replace=TRUE)
)

SQL 内连接让我参与其中:

df<-sqldf("SELECT a.start, a.stop, a.annotation, b.effect, b.position
FROM a, b
inner JOIN a b on(b.position >= a.start and b.position <= a.stop);")

但这并不能解释每条染色体位置的重复。我在将其包装到循环或应用函数中时遇到概念上的问题。

我对 SQL 并不执着,这只是我以前解决一个更简单问题的方式。我也不确定制作额外的索引列是否合适,因为我有数千个染色体值。

我想要的输出如下所示:

    df$chr<-c("NA","2","2")
start stop annotation effect position chr
1 1 11 this high 3 NA
2 1 11 this high 10 NA
3 11 21 this low 14 2

每个 position 都位于正确 chr 上的 startstop 点之间,或者给定NA,其中 chr 上没有任何点匹配。

最佳答案

development version data.table 引入了非相等连接,允许:

library(data.table)
setDT(a) # converting to data.table in place
setDT(b)

b[a, on = .(position >= start, position <= stop), nomatch = 0,
.(start, stop, annotation, effect, x.position, chr = ifelse(i.chr == x.chr, i.chr, NA))]
# start stop annotation effect x.position chr
#1: 1 11 this high 3 NA
#2: 1 11 this high 10 NA
#3: 11 21 this low 14 2

关于R,在向量化的范围内加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37147441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com