【问题标题】:Compare two data.frame and delete rows with common characters比较两个 data.frame 并删除具有常见字符的行
【发布时间】:2018-12-07 00:55:18
【问题描述】:

我有两个 data.frame x1 & x2。如果在 x1 和 x2 中发现共同基因,我想从 x2 中删除行

x1 <- chr   start   end         Genes   
      1      8401    8410      Mndal,Mnda,Ifi203,Ifi202b    
      2      8001    8020      Cyb5r1,Adipor1,Klhl12    
      3      4001    4020      Alyref2,Itln1,Cd244  

x2 <- chr   start   end         Genes
      1      8861   8868       Olfr1193 
      1      8405    8420      Mrgprx3-ps,Mrgpra1,Mrgpra2a,Mndal,Mrgpra2b   
      2      8501    8520      Chia,Chi3l3,Chi3l4   
      3      4321    4670      Tdpoz4,Tdpoz3,Tdpoz5 



x2 <- chr   start   end         Genes   
      1      8861   8868       Olfr1193
      2      8501    8520      Chia,Chi3l3,Chi3l4   
      3      4321    4670      Tdpoz4,Tdpoz3,Tdpoz5 

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    你可以试试

    x2[mapply(function(x,y) !any(x %in% y), 
            strsplit(x1$Genes, ','), strsplit(x2$Genes, ',')),]
    #  chr start  end                Genes
    #2   2  8501 8520   Chia,Chi3l3,Chi3l4
    #3   3  4321 4670 Tdpoz4,Tdpoz3,Tdpoz5
    

    或将!any(x %in% y) 替换为length(intersect(x,y))==0

    注意:如果“基因”列是“因子”,请将其转换为“字符”,因为strsplit 不能采用“因子”类。即strsplit(as.character(x1$Genes, ','))

    更新

    基于'x2'的新数据集,我们可以merge'chr'列的两个数据集,strsplit'Genes.x','Genes.y'来自输出数据集('xNew '),根据'Genes.y'字符串中'Genes.x'的任何元素的出现获取逻辑索引,使用它来子集'x2'数据集

     xNew <- merge(x1, x2[,c(1,4)], by='chr')
     indx <- mapply(function(x,y) any(x %in% y), 
          strsplit(xNew$Genes.x, ','), strsplit(xNew$Genes.y, ','))
     x2[!indx,]
     # chr start  end                Genes
     #1   1  8861 8868             Olfr1193
     #3   2  8501 8520   Chia,Chi3l3,Chi3l4
     #4   3  4321 4670 Tdpoz4,Tdpoz3,Tdpoz5
    

    【讨论】:

    • akrun,如果两个 data.frame 的长度不同怎么办。我已经更新了示例
    • @Kryo 使用新示例更新了帖子
    猜你喜欢
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2013-02-27
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多