首页 > 解决方案 > 仅当尚未在列表中(来自多个数据集)时,如何将元素添加到列表中

问题描述

我正在处理多个基因表达数据集(每个患者一个数据集)。我正在尝试制作一个矩阵,其中每列包含所有基因,每个患者的表达数据都在基因下。

问题是某些数据集缺少或未列出基因,因此我不一定对所有基因都有参考。

所以我实际上是在尝试编写一个代码来记录数据集中的所有基因,然后只在该列表中不存在的情况下将其他基因添加到该列表中。

请参见下面的示例:

我想从两个数据集中列出独特的基因:

Dataset 1                   Dataset 2
Gene     expression         Gene     expression
a        0.3                a        0.1
b        0.1                c        -0.3
e        0.2                d        0.05
f        0.2                f        -0.1


Ideal Output:
Genes = (a,b,c,d,e,f)

Instead I have been getting this output
Genes = (a,a,b,b,c,c,d,d,e,e,f,f,)

但是,当我尝试下面的代码时,我会收到此警告消息。 In if (!(copynumber_df$gene %in% genes)) { ... : the condition has length > 1 and only the first element will be used

此外,由于某种原因,输出中的每个基因都列出了两次(所以我最终得到了我预期的两倍)。

为什么每个基因都被添加到列表中两次?

copynumber_files <- list.files(data_dir) ###only 10 datasets/patients listed here 

genes <- c()


for (copynumber_file in copynumber_files){
  copynumber_df <- read.csv(copynumber_file, sep="\t")
  for (i in 1:nrow(copynumber_df)){
    if (copynumber_df$gene %in% genes == FALSE){
      genes <- append(genes, copynumber_df$gene)
    }
    else {}
    }
  
}

标签: rfor-loop

解决方案


推荐阅读