【问题标题】:Random sampling based on vector with multiple conditions R基于多条件向量的随机抽样R
【发布时间】:2019-11-17 17:13:12
【问题描述】:

我有一个包含 150000 行和 3 列的大型数据框 SYN_data,分别名为 SNP、Gene 和 count。有一个包含 2545 个计数值的列表 r,其中还包括一些重复项。现在我需要从 SYN_data 中随机抽样 2545 行而不替换,其计数值与列表 r 中的相似。通过使用此代码,我可以成功地做到这一点:

test1 <- SYN_data[ sample( which( SYN_data$count %in% r ) , 2545 ) , ]

第二个条件是Genes的唯一长度应该是1671,总共2545行,意味着有些Genes有超过1个SNP。有什么方法可以将此条件合并到同一代码中,或者满足所有条件的任何其他代码都会非常有帮助。谢谢!

样本数据:

# list
r 
> 1,7,3,14,9

SYN_data$SNP <- c('1- 10068526', '1- 10129891', '1- 10200104', 
                  '1- 10200491', '1- 10470141', '1- 10671598')

SYN_data$Gene <- c('AT1G28640', 'AT1G29030', 'AT1G29180', 
                   'AT1G29180', 'AT1G29900', 'AT1G30290')

SYN_data$count <- c('14',  '9',  '3',  '3',  '7',  '1')

【问题讨论】:

  • 所以您只希望样本中每个基因有 1 个 snp?
  • 我会说有多个snp的基因很少,只有一个snp的基因很少。重要的是 2545 个 snps 中的 1671 个独特基因的总数,其他相同计数值的条件也应满足列表 r。

标签: r random bioinformatics sample


【解决方案1】:

尝试使用以下方法:

library(dplyr)

no_of_rows <- 2545
no_of_unique_gene <- 1671
temp <- SYN_data

while(n_distinct(temp$Gene) != no_of_unique_gene) {
  gene <- sample(unique(SYN_data$Gene),no_of_unique_gene)
  temp <- SYN_data[SYN_data$V23 %in% unique(r) & SYN_data$Gene %in% gene, ]
}
part1  <- temp %>% group_by(Gene) %>% sample_n(floor(no_of_rows/no_of_unique_gene))
part2 <- temp %>% anti_join(part1) %>% sample_n(no_of_rows - nrow(part1)) 
final <- bind_rows(part1, part2)

现在检查length(unique(final$Gene))

【讨论】:

  • @RonaqShah 谢谢你的回答,这个代码的唯一问题是数据框“数据”没有显示 1671 个独特的基因,而是给出了一个每次都会变化的随机数。我可以把实际的数据集发给你,让你看看吗?
  • @amarah 当然...您可以使用dput 更新帖子中的前 100 行数据吗? dput(head(SYN_data, 100)) 。 ?
  • @amarah 我已经更新了答案。你现在可以检查吗?
【解决方案2】:

一种可能的方法是首先对 1671 个独特的基因进行采样,将数据集子集为共享这些基因并计数在 r 集合中的那些。这是data.table中这种方法的实现:

#had to create some dummy data as not clear what the data is like
set.seed(0L)
nr <- 15e4
nSNP <- 1e3 
nGene <- 1e4
ncount <- 1:14     
r <- c(1,3,7,9,14)
SYN_data <- data.table(SNP=sample(nSNP, nr, TRUE),
    Gene=sample(nGene, nr, TRUE), count=sample(ncount, nr, TRUE))

ncnt <- 2545
ng <- 1671

#sample 1671 genes
g <- SYN_data[, sample(unique(Gene), ng)]    

#subset and sample the dataset
ix <- SYN_data[Gene %in% g & count %in% r, sample(.I, 1L), Gene]$V1
ans <- rbindlist(list(
    SYN_data[ix],
    SYN_data[-ix][Gene %in% g & count %in% r][, .SD[sample(.I, ncnt - ng)]]))
ans[, uniqueN(Gene)]
#1662 #not enough Gene in this dummy dataset

输出:

      SNP Gene count
   1: 816 1261    14
   2:   7 8635     1
   3: 132 7457     1
   4:  22 3625     3
   5: 396 7640     7
  ---               
2534: 423 6387     3
2535: 936 3908     7
2536: 346 9654    14
2537: 182 7492     3
2538: 645  635     1

【讨论】:

  • 谢谢@chinsoon12,这是一个很好的方法,但是当我用相同的例子重新运行你的代码时,最终的数据集没有显示唯一的 1671 基因,我想这可能是因为 replace 设置为 TRUE。如果我将其设置为 FALSE,则有关数据框大小的错误。有什么办法可以解决这个错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2017-11-16
  • 2018-11-24
  • 1970-01-01
相关资源
最近更新 更多